gpt4 book ai didi

javascript - "React has detected a change in the order of Hooks"但 Hooks 似乎按顺序调用

转载 作者:数据小太阳 更新时间:2023-10-29 04:45:03 26 4
gpt4 key购买 nike

我正在尝试通过 React 的钩子(Hook)使用 ContextReducers,但遇到了钩子(Hook)顺序不固定的问题。我的理解是,只要 useHook(…) 的顺序保持不变,就可以在任何类型的控制流中调用返回的状态/更新函数/reducer。否则,我将在 FunctionComponents 的最开始调用 Hook 。

是不是我在循环中生成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-dnduseDrop 的引用。

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 Hook ,也像此处一样在顶层调用)。

const Day: FunctionComponent<DayProps> = ({ date, height, children }) => {
const dispatch = useContext(State.DispatchContext)
const [{ isOver, offset }, dropRef] = useDrop({
// …uses the dispatch function within…
// …
})
// …
}

最佳答案

由于使用短路逻辑,我在编写的组件中遇到了同样的错误消息。

这导致了一个错误:

const x = useSelector(state => state.foo);
if (!x) { return ; }
const y = useSelector(state => state.bar);

这是因为当 x 为真时,钩子(Hook)列表的长度为 2,但当 x 为假时,列表的长度为 1。

为了解决这个错误,我必须在任何提前终止之前使用所有钩子(Hook)。

const x = useSelector(state => state.foo);
const y = useSelector(state => state.bar);
if (!x) { return ; }

关于javascript - "React has detected a change in the order of Hooks"但 Hooks 似乎按顺序调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com