最佳答案
我试图使用 Context
和 Reducers
通过反应的钩子,并遇到问题与钩子的顺序不是恒定的。我的理解是,只要 useHook(…)
的顺序保持不变,就可以在任何类型的控制流中调用返回的 state/update 函数/reduce。否则,我将在 FunctionComponent 的最开始调用钩子。
是我在循环生成 Days
? 还是遗漏了什么?
Warning: React has detected a change in the order of Hooks
called by Container. This will lead to bugs and errors if not fixed. For
more information, read the Rules of Hooks:
https://reactjs.org/docs/hooks-rules.html
Previous render Next render
------------------------------------------------------
1. useContext useContext
2. undefined useRef
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
下面是 Container
的完整版本。下面是 Day
的节选,以及 react-dnd
的 useDrop
的参考文献。
export const Container: FunctionComponent<Props> = () => {
let events = useContext(State.StateContext)
//let events: Array<Event.Event> = [] <- with this, no warning
const getDaysEvents = (day: Event.Time, events: Array<Event.Event>) => {
return events.map(e => {
const isTodays = e.startTime.hasSame(day, "day")
return isTodays && Event.Event({ dayHeight, event: e })
})
}
let days = []
for (let i = 0; i < 7; i++) {
const day = DateTime.today().plus({ days: i })
days.push(
<Day key={day.toISO()} height={dayHeight} date={day}>
{getDaysEvents(day, events)}
</Day>
)
}
return <div className="Container">{days}</div>
}
摘自 Day
(Event
类似地使用 useDrag
钩子,也像这里一样在顶层调用)。
const Day: FunctionComponent<DayProps> = ({ date, height, children }) => {
const dispatch = useContext(State.DispatchContext)
const [{ isOver, offset }, dropRef] = useDrop({
// …uses the dispatch function within…
// …
})
// …
}