Reactjs 反应钩中的状态

Reactjs 反应钩中的状态,reactjs,react-hooks,Reactjs,React Hooks,如何在功能组件中使用带有useEffect的prevState?我被告知要将类组件更新为功能组件,我被困在使用prevState的componentDidUpdate部分 componentDidUpdate(prevProps, prevState) { if (prevState.search !== this.state.search) { this.getData() } if (prevState.finalSearch !== this.stat

如何在功能组件中使用带有useEffect的prevState?我被告知要将类组件更新为功能组件,我被困在使用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}
        />
componentDidUpdate(prevProps,prevState){
if(prevState.search!==this.state.search){
这个文件名为getData()
}
如果(prevState.finalSearch!==此.state.finalSearch){
if(this.state.finalSearch){
这是newData()
}否则{
这个文件名为getRawData()
}
}
}

您没有类内生命周期组件的prevState,但是 我想这里的答案可能会对你有所帮助,只是为了道具,让它成为国家


因此,看起来您只是在使用前一个状态,以避免不必要的渲染。这实际上是一个非常常见的问题,它内置于
useffect

componentDidUpdate(prevProps,prevState){
if(prevState.count!==this.state.count){
document.title=`您单击了${this.state.count}次';
}
}
变成:

useffect(()=>{
document.title=`您单击了${count}次`;
},[count]);//仅在计数更改时重新运行效果
资料来源:

您的组件可能看起来像:

useffect(()=>{
getData()
if(最终搜索){
新数据()
}否则{
getRawData()
}
},[搜索,最终搜索];

您必须创建自定义挂钩
usePrevious
,请参阅以下内容:

那么你必须这样做:

const Component = (props) => {
   const {search, setSearch} = useState('');
   const prevSearch = usePrevious({search, setSearch});
   useEffect(() => {
      if(prevSearch.search !== search) {
          //Your code goes here
      }
   }, [search])
}

你能发布更多的代码并澄清一下吗?很难说出你的问题是什么或你到底在问什么。通常,如果您使用的是
useffect
您没有使用
componentdiddupdate
,因此我对您的问题感到有点困惑。我被告知要将一个类组件更新为functional component,代码中有这个componentdiddupdate,我不知道如何将其更改为useffect@otwd回答您的问题吗?另外请查看@反应新手你说什么是错的?你是说为什么它不渲染?我在这里看不到你问题中的代码。@reactRookie我看到的是
/src/App.js:Unexpected token(159:0)
@reactRookie我更新了我的答案,以获得我认为你的组件应该是什么样子。您不需要
useproval
@reactRookie函数加下划线只是您的编译器告诉您有错误。如果你把鼠标移到它上面,它会告诉你原因。这段代码似乎有很多不同的问题。@reactRookie当我输入一些东西时,当你选择一个结果时,它似乎工作得很好。如果您只是说单击并选择一个结果时什么也看不到,那么模糊函数看起来并不是在修改任何状态。因此,由于它们只使用以前的值来检测是否需要渲染,因此您不需要自定义挂钩,它内置于
useffect
:@otw yes,对于这种特殊情况,我们可以使用
useffect
hook。但是,如果我们想使用
prevState
值(例如,我们有一个复选框,根据以前的值,我们需要更改它),那么上述方法将特别解决该问题。因此,根据情况,我们可以寻找最佳方法,并将其应用于解决问题。
const Component = (props) => {
   const {search, setSearch} = useState('');
   const prevSearch = usePrevious({search, setSearch});
   useEffect(() => {
      if(prevSearch.search !== search) {
          //Your code goes here
      }
   }, [search])
}