【问题标题】:React.memo reset state to previousReact.memo 将状态重置为上一个
【发布时间】:2020-06-08 19:47:03
【问题描述】:

我有一个包含行的表,每一行都有一个更新该行的操作按钮。

当我不使用 React.memo 时,一切正常。如果我将 rows 组件放入 React.memo 中,第一次更新就可以了,但是下一个更新当前行,而前一个返回到初始状态。

我正在使用 reducer 更新状态,当我使用 console.log 状态时,它会按预期更新。但是当我从下一行单击操作按钮时,它使用前一个状态作为起点,然后将前一行返回到初始值。

下一行的操作按钮似乎保留了对先前状态的引用,因为它没有重新渲染。

以下是代码的主要部分:

function reducer(state, action) {
    switch (action.type) {
    ....
        case 'update':
            return { ...state, result: action.payload };
        default:
            throw new Error("Unknown state action");
    }
}

const [state, dispatch] = useReducer(reducer, { loading: initialLoading, result: null });

const result = state.result;
const loading = state.loading;

// Called from the row action button
const handleUpdateResult = React.useCallback(index => data => {
      // When called from the next row action button - result keeps old state, even component rendered row with new values
      const newConnection = {
          ...result.connections[index],
          status: data.status
      };

      const newConnections = [...result.connections.slice(0, index), newConnection, ...result.connections.slice(index + 1)];
      const updatedResult = { ...result, connections: newConnections };

      setResult(updatedResult);
}, [result, setResult]);


const setResult = useCallback((newState) => {
    dispatch({ type: "update", payload: newState });
}, []);

任何想法我做错了什么:/...

【问题讨论】:

    标签: reactjs react-hooks memo


    【解决方案1】:

    也许有人会有同样的情况,所以我将解释问题和解决方案。

    问题是handleUpdateResult 正在使用当前状态。我在文档的某个地方读到,每当您更新状态并且需要当前状态时,请使用 reducer。我实际上正在使用减速器,但我仍然在函数handleUpdateResult 中使用了当前状态,这会造成一些混乱:)。

    无论如何,我没有使用那里的状态,而是向 reducer 发送一个动作来更新值,一切正常:

    // Called from the row action button
    const handleUpdateResult = React.useCallback((index, newStatus) => row => {
          const newRow = {
              ...row,
              status: newStatus
          };
    
          setResult({
              action: "updateRow",
              payload: {
                  index: index,
                  row: newRow
              }
          });
    }, [setResult]);
    

    当result 状态从函数中移除,并从reducer 中使用当前状态时,一切正常。更新行的逻辑移到reducer。

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      相关资源
      最近更新 更多