最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

仅在状态更新时执行获取请求

IT培训 admin 9浏览 0评论

仅在状态更新时执行获取请求

我是React的新手,我正在试图弄清楚如何正确使用fetch。我有一个React组件,我想在远程服务器更新其父级状态时从远程服务器更新。

即 - 父状态已更改 - > myComponent调用远程服务器并重新呈现自身。

我尝试过以下方法:

如果我只对fetch执行.componentDidMount调用,它会忽略任何状态更新。

如果我在fetch上执行.componentDidUpdate调用,它会无休止地调用服务器(我假设因为一些更新渲染循环)

我尝试过使用componentWillReceiveProps函数,它可以工作,但我知道它现在已被弃用了。没有componentWillReceiveProps,我怎样才能实现这种行为?

class myComponent extends React.Component {

constructor(props) {
super(props);
this.state = {
  images: []
};
}

componentDidMount() {

let server = "somethingserver.html";
fetch(server)
  .then(res => {
    if (res.ok) {
      return res.json();
    }
    else {
      console.log(res);
      throw new Error(res.statusText);
    }
  })
  .then(
    (result) => {
      this.setState({
        images: result.items
      });
    }
  ).catch(error => console.log(error));
}
componentWillReceiveProps(nextprops) {
if (this.state !== nextprops.state) {
    //same as componentDidMount
    }
}

render() {
 return (
   <Gallery images={this.state.images} enableImageSelection={false} />
);
}
}
回答如下:

你可以使用getDerivedStateFromProps。这是componentWillReceiveProps的更新版本。

你也应该读这个:https://reactjs/blog/2018/06/07/you-probably-dont-need-derived-state.html

使用props更新组件中的内部状态可能会导致复杂的错误,并且通常有更好的解决方案。

仅在状态更新时执行获取请求

我是React的新手,我正在试图弄清楚如何正确使用fetch。我有一个React组件,我想在远程服务器更新其父级状态时从远程服务器更新。

即 - 父状态已更改 - > myComponent调用远程服务器并重新呈现自身。

我尝试过以下方法:

如果我只对fetch执行.componentDidMount调用,它会忽略任何状态更新。

如果我在fetch上执行.componentDidUpdate调用,它会无休止地调用服务器(我假设因为一些更新渲染循环)

我尝试过使用componentWillReceiveProps函数,它可以工作,但我知道它现在已被弃用了。没有componentWillReceiveProps,我怎样才能实现这种行为?

class myComponent extends React.Component {

constructor(props) {
super(props);
this.state = {
  images: []
};
}

componentDidMount() {

let server = "somethingserver.html";
fetch(server)
  .then(res => {
    if (res.ok) {
      return res.json();
    }
    else {
      console.log(res);
      throw new Error(res.statusText);
    }
  })
  .then(
    (result) => {
      this.setState({
        images: result.items
      });
    }
  ).catch(error => console.log(error));
}
componentWillReceiveProps(nextprops) {
if (this.state !== nextprops.state) {
    //same as componentDidMount
    }
}

render() {
 return (
   <Gallery images={this.state.images} enableImageSelection={false} />
);
}
}
回答如下:

你可以使用getDerivedStateFromProps。这是componentWillReceiveProps的更新版本。

你也应该读这个:https://reactjs/blog/2018/06/07/you-probably-dont-need-derived-state.html

使用props更新组件中的内部状态可能会导致复杂的错误,并且通常有更好的解决方案。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论