首页 > 解决方案 > 反应钩子中的prevstate

问题描述

如何在功能组件中使用 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}
        />

标签: reactjsreact-hooks

解决方案


所以看起来你只是使用以前的状态来避免这里不必要的渲染。这实际上很常见,它内置于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]);

推荐阅读