Javascript 如果我尝试在axios中设置state,在React中捕获错误,则会得到无限量的get 404错误

Javascript 如果我尝试在axios中设置state,在React中捕获错误,则会得到无限量的get 404错误,javascript,reactjs,Javascript,Reactjs,我试图在Axios React中设置捕获承诺的内部状态,它可以工作,但我得到了无限量的请求和404错误 class Search extends Component { state = { notFound: false, dataResult: "", }; componentDidUpdate() { axios .get("url") .then((resp) => {

我试图在Axios React中设置捕获承诺的内部状态,它可以工作,但我得到了无限量的请求和404错误

class Search extends Component {
  state = {
    notFound: false,
    dataResult: "",
  };

  componentDidUpdate() {
    axios
      .get("url")
      .then((resp) => {
        this.setState({ dataResult: resp.data });
      })
      .catch((err) => {
        if (err.response.status === 404) {
          this.setState({ notFound: true });
        }
      });
  }

  render() {
    return (
      <div>
        {this.state.notFound ? <div>NOTFOUND</div> : null}
      </div>
    );
  }
}

类搜索扩展组件{
状态={
notFound:错误,
数据结果:“”,
};
componentDidUpdate(){
axios
.get(“url”)
。然后((resp)=>{
this.setState({dataResult:resp.data});
})
.catch((错误)=>{
if(err.response.status==404){
this.setState({notFound:true});
}
});
}
render(){
返回(
{this.state.notFound?notFound:null}
);
}
}
控制台结果(URL是API):

获取“url”404(未找到) 获取“url”404(未找到) 获取“url”404(未找到)

您可以在componentDidUpdate()中立即调用setState(),但请注意 必须将其包装在与上述示例类似的条件中,或者 你将导致一个无限循环


如果您需要在某些输入状态发生更改时调用axios,那么您需要使用某些条件包装该调用,以便仅在输入状态实际发生更改时调用它
componentDidUpdate
方法是使用以前的状态对象调用的。因此,您可以将以前的状态与当前状态进行比较,以确保该状态实际上已更改

componentDidUpdate(prevProps, prevState) {
  if(prevState.myInputState !== this.state.myInputState) {
    axios
      .get("url")
      .then((resp) => {
        this.setState({ dataResult: resp.data });
      })
      .catch((err) => {
        if (err.response.status === 404) {
          this.setState({ notFound: true });
        }
      });
  }
}

使用
componentDidMount
函数而不是
componentDidUpdate
来避免无限调用。@PrakashSharma我需要在更新输入状态时提取数据。然后在条件中包装该调用,以便仅在更新输入状态时调用它,而不是每次都调用。@PrakashSharma我如何检查状态是否在未更新的情况下更新使用
componentdiddupdate
?检查答案。
componentDidUpdate(prevProps, prevState) {
  if(prevState.myInputState !== this.state.myInputState) {
    axios
      .get("url")
      .then((resp) => {
        this.setState({ dataResult: resp.data });
      })
      .catch((err) => {
        if (err.response.status === 404) {
          this.setState({ notFound: true });
        }
      });
  }
}