最大更新超出(useEffect + Redux Hooks)



我使用Redux钩子。我试图从useEffect调度,但得到错误"最大更新超过">

const state = useSelector((state: RootStateOrAny) => ({data: state}));
const dispatch = useDispatch();
React.useEffect(() => {
if (state.data.topics.topics === null) dispatch({type: 'GET_TOPICS'});
console.log(state.data.topics.topics)
}, [dispatch, state]);

在分配给Redux的每个操作上,state被重新创建。例如,查看

下面的示例reducer
const reducer = (state, action) => {
switch(action.type) {
case 'ACTION1":
return { ...state, prop: action.prop }
//...
}
}

dispatch({ type: 'ACTION1', prop: 'something' })被调用时,接收到新的状态对象。并且每次调用dispatch时都会接收到新的状态对象。

useEffect的依赖数组中有stateuseEffect比较依赖使用对象。是检测变化。因此,当调用dispatch后获得新状态时,useEffect再次触发并调用dispatch。这将创建无限循环。

要打破循环,您需要使useSelector更具体。不要选择完全状态,只选择你将要使用的道具。

const topics = useSelector((state: RootStateOrAny) => state.topics.topics);
const dispatch = useDispatch();
React.useEffect(() => {
if (topics === null) dispatch({type: 'GET_TOPICS'});
console.log(topics)
}, [dispatch, topics]);