gpt4 book ai didi

javascript - 延迟 componentDidMount 获取 this.props 被读取

转载 作者:行者123 更新时间:2023-11-30 14:26:20 25 4
gpt4 key购买 nike

我正在从 componentDidMount 中获取 data 作为

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/${this.props.id} 替换 https://api.example.com/location/12345 允许更改 id 我收到数据不存在的错误。

这显然是因为 componentDidMount 中的 fetch 正在读取 this.props.id 之前的 url。

如何延迟 fetch 直到 this.props.id 可用?

最佳答案

一种方法是,使用 componentDidUpdate生命周期方法在组件收到新 id 时获取数据,但请确保将 previd 值与新 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 }));
}

关于javascript - 延迟 componentDidMount 获取 this.props 被读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51891218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com