道具更改后,React何时应调用AJAX请求?

时间:2020-04-13 02:51:03

标签: reactjs react-lifecycle

我以前在ComponentWillReceiveProps()更改道具后给AJAX打电话

componentWillReceiveProps(nextProps) {
    if(nextProps.foo !== this.props.foo){
       //fetch & call this.setState() asynchronously
    }
}

React 16.3之后ComponentWillReceiveProps()将在未来被弃用。除了ComponentWillReceiveProps()之外,还有一个新功能getDerivedStateFromProps,但我无法更新状态异步。

static getDerivedStateFromProps(nextProps, prevState) {
    // I can't get access to this.props but only state

    if(nextProps.foo !== this.props.foo){
       //fetch & call this.setState() asynchronously
    }

    // I can only return a state but update it after an AJAX request
    return {}
}

最佳做法是什么。

2 个答案:

答案 0 :(得分:2)

进行异步调用的最佳位置是componentDidUpdate(prevProps, prevState, snapshot) {}getDerivedStateFromProps是静态方法,因此它无法访问组件实例(无法访问this

答案 1 :(得分:1)

您不应使用getDerivedStateFromProps生命周期进行api调用。相反,使用componentDidUpdate进行api调用,一旦获得api响应,就执行this.setState。另外,正如另一个答案所指出的那样,您不能在静态方法中使用this

componentDidUpdate(prevProps) {
    if (this.props.myData !== prevProps.myData) {
      this.callMyApi();
    }
}

callMyApi() {
  fetch("/api")
    .then(response => {
      this.setState({ ... });
    })
}

如果您正在编写新组件,则还可以考虑编写功能组件,并在更新属性时使用useStateuseEffect来触发api调用。

赞:

...
  const {page} = this.props;
  const [images, setImages] = useState([]);

  useEffect(() => {
    fetch(`/myfavApi`)
      .then(data => data.json())
      .then(images => {
        setImages(images.concat(images));
      });
  }, [page]); // provide page(prop) as dependency. 
  ...