react-window 行调用 useState
react-window rows call useState
我正在尝试在 react-window rows (using FixedSizeList), but their state (useState
) is not maintained when they get re-rendered so it resets every time I scroll back to them. This makes sense because they're getting unmounted, but is there a way prevent re-rendering via memo
or useCallback
? I've seen some examples of avoiding re-renders, but I can't get them working. In this example sandbox 中渲染一个有状态的组件,我尝试记忆一个只需要一个 prop 的组件 (<InnerRow>
),但它似乎保持重新- 无论调用 memo
.
是我没有正确记忆还是做错了什么?或者这是不可能的,我唯一的解决方案是在行组件之外以其他方式维护状态。
您可以尝试使用 useReducer
而不是 memo
。 Reducer 将帮助您保持点击组件的状态,即使它们没有安装在 dom.
function reducer(state, action) {
switch (action.type) {
case "add": {
return {
isOn: [...state.isOn, action.payload]
};
}
case "remove": {
const newArray = [...state.isOn];
const newState = newArray.filter((a) => a !== action.payload);
return {
isOn: newState
};
}
default:
throw new Error();
}
}
你可以在这里查看我的解决方案:https://codesandbox.io/s/keen-mclaren-nenc9v?file=/src/App.js
经过更多研究,我认为我的问题的答案是:No
不可能。如果不再安装该内存,它究竟会存放在哪里?我必须将状态保存在其他地方,比如在父组件中,或者通过全局状态。
我正在尝试在 react-window rows (using FixedSizeList), but their state (useState
) is not maintained when they get re-rendered so it resets every time I scroll back to them. This makes sense because they're getting unmounted, but is there a way prevent re-rendering via memo
or useCallback
? I've seen some examples of avoiding re-renders, but I can't get them working. In this example sandbox 中渲染一个有状态的组件,我尝试记忆一个只需要一个 prop 的组件 (<InnerRow>
),但它似乎保持重新- 无论调用 memo
.
是我没有正确记忆还是做错了什么?或者这是不可能的,我唯一的解决方案是在行组件之外以其他方式维护状态。
您可以尝试使用 useReducer
而不是 memo
。 Reducer 将帮助您保持点击组件的状态,即使它们没有安装在 dom.
function reducer(state, action) {
switch (action.type) {
case "add": {
return {
isOn: [...state.isOn, action.payload]
};
}
case "remove": {
const newArray = [...state.isOn];
const newState = newArray.filter((a) => a !== action.payload);
return {
isOn: newState
};
}
default:
throw new Error();
}
}
你可以在这里查看我的解决方案:https://codesandbox.io/s/keen-mclaren-nenc9v?file=/src/App.js
经过更多研究,我认为我的问题的答案是:No
不可能。如果不再安装该内存,它究竟会存放在哪里?我必须将状态保存在其他地方,比如在父组件中,或者通过全局状态。