【问题标题】:Can the updater function in useState be redefined in React?可以在 React 中重新定义 useState 中的 updater 函数吗?
【发布时间】:2020-03-09 15:33:19
【问题描述】:

我正在开发一个使用商店对象的相当复杂的组件。数据是本地的,因此不保证将其添加到我的 Redux 存储中,但足够昂贵以至于不应该在每次渲染时都计算它。我使用useState 来存储和更新这个对象。但是,我有几个关于商店的功能,我想将它们分解成一个新文件,包括更新程序功能。例如,我想做类似这样的事情:

import { storeUpdater } from './ComponentStore.js';
function MyComponent(props) {
  const updateStore = storeUpdater;
  let storeState = useState({});
  const store = storeState[0];
  storeState[1] = updateStore;
  ...
}

这是否可靠,更重要的是,它是否违反了任何规则/反模式?

【问题讨论】:

    标签: reactjs react-hooks use-state


    【解决方案1】:

    这应该行不通。您只是将您定义的storeState[1] 重新分配给不同的函数,而不是useState 提供的setState。此代码根本不应该更新您的storeState[0]

    相反,您应该让您的 storeUpdater 函数将 setState 函数作为参数并在此组件中提供它。

    function storeUpdater(setState) {...}

    const updateStore = () => storeUpdater(storeState[1])

    然后,在您的updateStore 中,对storeState 进行所需的修改,然后将新状态传递给setState。如果新状态依赖于之前的状态,可以使用setState(prevState => nextState)语法。

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 2023-03-16
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2021-11-27
      • 2019-01-06
      相关资源
      最近更新 更多