调试对许多重新渲染错误反应 redux

时间:2021-07-16 11:52:15

标签: reactjs react-redux react-hooks

我遇到了这些代码行抛出 Too many re-renders. React limits the number of renders to prevent an infinite loop 错误的问题。任何人都可以帮我找出导致此问题的原因吗?

options = useSelector(state => {
        if(!props.disabled) {
            if(props.values) {
                return props.values
            } else if(props.dispatch) {
                dispatch({type: props.dispatch});
                return state[props.getFrom] ? state[props.getFrom] : []
            }
        } else {
            return [];
        }
    }); 

基本上这里的用例是,在组件加载时,我想调用一个调度,其中 api 将被命中并且结果将存储在 redux 存储中。然后我想在同一个组件的下拉列表中呈现这些值!

提前致谢!

1 个答案:

答案 0 :(得分:0)

以下行可能会导致组件重新渲染并导致无限循环:dispatch({ type: props.dispatch }); 也许您应该将其放入效果中:

//do not change reference to returning empty array
//  this can cause the component to re render
const EMPTY = [];
const Component = ({ disabled, values, dispatch, getFrom }) => {
  //I assume dispatch does not change and is from
  //  connect or useDispatch
  React.useEffect(() => {
    if (!values && !disabled && dispatch) {
      dispatch({ type: dispatch });
    }
  }, [disabled, dispatch, values]);
  const options = useSelector((state) => {
    if (!disabled && values) {
      return values;
    }
    if(!disabled && state[getFrom]){
      return state[getFrom];
    }
    else {
      return EMPTY;
    }
  });
};