Redux probleb Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

Redux probleb Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

如果我写这篇文章会出现错误:重新渲染太多。 React 限制渲染次数以防止无限循环。

var dispatch = useDispatch()
var phone = useSelector(store => store.phone)
 dispatch(phonePagePhone(window.location.href.split('/').splice(-1)))

但是如果我写这个没有错误:

 var phone = useSelector(store => store.phone)

为什么如果我在同一个文件中使用 useSelector 和 useDispatch grtting 错误:操作必须是普通对象。使用自定义中间件进行异步操作。终极版

您应该在回调中调度,而不是在您的组件主体中调度。

像这样:

const MyComponent = () => {
   const dispatch = useDispatch(); 
   const phone = useSelector(...);

   const handleSomeUserInitiatedAction = () => {
      dispatch(...);
   };
}

如果你想在第一次渲染时调度,你可以在 useEffect 中这样做:


const MyComponent = () => {
   const dispatch = useDispatch(); 
   const phone = useSelector(...);

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