React redux重新渲染太多。React限制渲染数量以防止无限循环

如何解决此错误。

这是我的代码。首先,我使用useSelector来调用我的减速器 和useEffect

const dispatch = useDispatch();
const calendarSelector = useSelector(state => state.calendarReducer);
const [stateEvents, setStateEvents] = useState(events);

useEffect(() => {
 dispatch(collection());
}, [dispatch]);

然后在我的calendarSelector.loading为false,直到他从api获取数据为止

if (!calendarSelector.loading) { 
 const collection = calendarSelector.collection.events;
 console.log('events ->', collection);
 setStateEvents(collection);
}

我在setStateEvents上收到我的错误,但是如果我使用setTimeout这样的话

setTimeout(() => setStateEvents(events));

它可以修复错误,但是if(!calendarSelector.loading){}可以继续运行

image of my console log

评论
  • 劫走EXO
    劫走EXO 回复

    The issue is that you are trying to update state directly inside render. You must instead use useEffect to update state when isLoading flag changes

    useEffect(() => {
    
        if (!calendarSelector.loading) { 
         const collection = calendarSelector.collection.events;
         console.log('events ->', collection);
         setStateEvents(collection);
        }
    
    }, [calendarSelector.loading]);
    

    但是,尽管上述方法可以解决您的问题,但您不得将道具复制到状态,除非您要中间更新本地状态

    You can directly use calendarSelector.collection.events in your component