【问题标题】:React-redux: Why is functional component rendering after updating redux state?React-redux:为什么更新redux状态后功能组件渲染?
【发布时间】:2020-03-30 15:28:58
【问题描述】:

为什么在 store 状态更改后,组件调度更新 react-redux 状态的操作会重新渲染?不应该只在 props 或组件状态发生变化时才重新渲染吗?

const BoxContainer=memo(({props})=>{


    const dispatch = useDispatch();

    //Setting action with dispatch with useCallBack hook for safe side

    const callAction =useCallback(
        (payload) => {
            dispatch(payload)
        },
        [],
    );
    const structure = useSelector(state => ({...state.FormState}));
    var form = generateForm(structure,callAction);

    return(   
        <React.Fragment>
                {form}
        </React.Fragment>

    );
});

Reducer 代码如下

export const FormState = (state = FormStructureState ,action) =>
{   
    switch(action.type){
        case 'UPDATE':
            return {
                ...state,
                Structure:action.Payload
            }
        case 'MOVEITEM':
              var sourceRow = action.sourceRow;
              var sourceCol = action.sourceCol;
              var destRow = action.destRow;
              var destCol = action.destCol;
              var destinationContent = state.Structure.row[destRow][destCol].content;
              state.Structure.row[destRow][destCol].content = state.Structure.row[sourceRow][sourceCol].content;
              state.Structure.row[sourceRow][sourceCol].content = destinationContent;
              return {...state}
        case 'SETTEMPLATE':
              var sourceRow = action.sourceRow;
              var sourceCol = action.sourceCol;
              state.Structure.row[sourceRow][sourceCol].content.template = action.template;
        default:
            return {...state}

    }


}

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    因为您的选择器每次都会无条件返回一个新对象:

    useSelector(state => ({...state.FormState}));
    

    useSelector will force a re-render if the return value is a new reference。不要那样做。

    另外,附带说明一下,您当前的 reducer 逻辑存在许多问题。特别是,这些行正在改变现有状态:

    state.Structure.row[destRow][destCol].content = state.Structure.row[sourceRow][sourceCol].content;
    

    不要那样做。

    还有一些风格问题:

    • 避免使用var
    • 使用解构语法提取变量,如const {sourceRow, sourceCol} = action

    我强烈建议您改用我们的official Redux Toolkit package,它会默认捕获意外突变,并允许您编写更简单的 reducer 逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2018-12-12
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多