仅在状态更新时执行获取请求
我是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更新组件中的内部状态可能会导致复杂的错误,并且通常有更好的解决方案。