reactjs - react 钩子(Hook)中的prevstate

标签 reactjs react-hooks

如何在功能组件中使用 prevState 和 useEffect?我被告知将类组件更新为功能组件,我被困在使用 prevState 的 componentDidUpdate 部分

 componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      this.getData()
    }
    if (prevState.finalSearch !== this.state.finalSearch) {
      if (this.state.finalSearch) {
        this.newData()
      } else {
        this.getRawData()
      }
    }
  }
 

<Search
          search={search}
          finalSearch={finalSearch}
        />

最佳答案

所以看起来你只是在使用以前的状态来避免不必要的渲染。这实际上很常见,它被内置到 useEffect 中:

componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    document.title = `You clicked ${this.state.count} times`;
  }
}

变成:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

来源:https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

您的组件可能看起来像:

useEffect(() => {
  getData()
  
  if (finalSearch) {
    newData()
  } else {
    getRawData()
  }
}, [search, finalSearch]);

关于reactjs - react 钩子(Hook)中的prevstate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62733408/

相关文章:

javascript - componentDidMount() 不工作但命中调试器

reactjs - react 钩子(Hook)如何确定它们用于的组件?

javascript - React HTML选择元素onChange函数,尝试访问 'event.target.value'

reactjs - 从父组件中执行子组件中的功能

javascript - 如何为我的应用程序中需要它的所有 React 组件提供窗口宽度?

javascript - React js 中的条件属性

reactjs - React Hooks Form Reset 不要将 Select 设置为初始值

javascript - 需要设置下拉值并根据初始下拉选择禁用

javascript - 如何仅在父元素中显示按钮?

javascript - 样式加载器不适用于 Webpack2