Javascript 延迟读取this.props的componentDidMount获取
我从Javascript 延迟读取this.props的componentDidMount获取,javascript,reactjs,Javascript,Reactjs,我从componentDidMountas中获取数据 this.setState({ isLoading: true }); fetch( `https://api.example.com/location/12345` ) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Something went wrong
componentDidMount
as中获取数据
this.setState({ isLoading: true });
fetch(
`https://api.example.com/location/12345`
)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => this.setState({ data, isLoading: false }));
这绝对有效。但是如果我想替换https://api.example.com/location/12345
与https://api.example.com/location/${this.props.id}
若要允许id
更改,则返回数据不存在的错误
这显然是因为componentDidMount
中的fetch
在读取This.props.id
之前获取url
如何延迟获取
,直到此.props.id
可用?一种方法是,每当组件接收到新id时,使用lifecycle方法获取数据,但确保将上一个id值与新id值进行比较,并且仅当它们不相同时才进行调用
像这样:
componentDidUpdate(prevProps) {
if(this.props.id && (prevProps.id != this.props.id)) {
this._getData();
}
}
_getData(){
this.setState({ isLoading: true });
fetch(
`https://api.example.com/location/${this.props.id}`
)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => this.setState({ data, isLoading: false }));
}
我经常使用这种模式:
initFromProps(props: MyComponentProps) {
const { } = props;
}
componentWillMount() {
this.initFromProps(this.props);
}
componentWillReceiveProps(nextProps: MyComponentProps) {
this.initFromProps(nextProps);
}
这可以确保组件在道具更改时以及启动时执行任何必要的操作。然后,在initFromProps
中,您可以执行以下操作:
initFromProps(props: MyComponentProps) {
const { id } = props;
if (id !== this.props.id) {
this._getData(id);
}
}
在新版本中,这两种方法都将被弃用,在16.3中,它们都带有不安全前缀。勾选此项,因此最好不要建议这些方法。:)不推荐使用componentWillMount和componentWillReceiveProps谢谢。出于某种原因,这对我不起作用,但我认为这可能是因为我使用的是
gatsby
v2,而现在使用的是reach-router
。你有什么错误吗?如果你解释这个问题,我会尽力帮助你:)不,但是如果我console.log(data)
它是未定义的,在一个按钮上调用相同的方法单击并检查,也在console.log(this.props.id)
内部\u getData
并验证值。我不认为位置
被解读为识别prevProps