简体   繁体   English

反应窗口行调用 useState

[英]react-window rows call useState

I'm trying to render a stateful component inside 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.我正在尝试在react-window行中渲染一个有状态的组件(使用 FixedSizeList),但是当它们被重新渲染时它们的状态( useState )不会被维护,所以每次我滚动回它们时它都会重置。 This makes sense because they're getting unmounted, but is there a way prevent re-rendering via memo or useCallback ?这是有道理的,因为它们正在被卸载,但是有没有办法防止通过memouseCallback重新渲染? I've seen some examples of avoiding re-renders, but I can't get them working.我见过一些避免重新渲染的例子,但我无法让它们工作。 In this example sandbox I've made, I tried memoizing a component ( <InnerRow> ) that only takes a single prop, but it seems to keep re-rending it regardless of calling memo .在我制作的这个示例沙箱中,我尝试记忆一个只需要一个道具的组件( <InnerRow> ),但无论调用memo ,它似乎都会继续重新渲染它。

Am I not memoizing correctly or doing something wrong?我没有正确记忆还是做错了什么? Or is this not possible, and my only solution is to maintain the state in some other way, outside of the row component.或者这是不可能的,我唯一的解决方案是在行组件之外以其他方式维护状态。

You can try by using useReducer instead of memo .您可以尝试使用useReducer而不是memo Reducer will help you maintain state of clicked components even if they are not mounted in dom. 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();
  }
}

You can check my solution here: https://codesandbox.io/s/keen-mclaren-nenc9v?file=/src/App.js你可以在这里查看我的解决方案: https ://codesandbox.io/s/keen-mclaren-nenc9v?file=/src/App.js

After some more research, I think that the answer to my question is: No Not possible.经过更多研究,我认为我的问题的答案是: No ,不可能。 Where exactly would that memory live if it's no longer mounted?如果不再挂载,那段内存究竟会在哪里? I'll have to keep the state elsewhere, like in the parent component, or via global state.我必须将状态保留在其他地方,例如在父组件中,或通过全局状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM