我想使用componentDidMount中的{this.state.whatever}动态化URL,但是失败了。因为状态值是不确定的(我运行console.log并且错误也显示了它)
我以为componentDidMount在状态重置后运行,所以我可以在URL中使用更新后的状态,但是不起作用,我想知道为什么
state={ breed: "" }
async componentDidMount(){
try {
const res = await
fetch(`https://dog.ceo/api/breed/${this.state.breed}/images`);
const data = await res.json();
const imageUrl = data.message;
this.setState({
puppyImage: imageUrl
})
} catch (error) {
console.log(error);
}
}
onChangeHandler = event => {
this.setState({breed: event.target.value})
};
由于未定义{this.state.breed},因此该URL不起作用,这意味着它尚未更新。错误显示:GET https://dog.ceo/api/breed//images 404
componentDidMount()
将只运行一个单一组件呈现之后,也再没有时间。
您应该使用componentDidUpdate()
在组件获得更新状态或道具时触发的触发器。在其中,您可以配置逻辑以确定是否应该执行new fetch
。
componentDidUpdate(prevProps, prevState){
if(prevState.breed !== this.state.breed){
try {
const res = await
fetch(`https://dog.ceo/api/breed/${this.state.breed}/images`);
const data = await res.json();
const imageUrl = data.message;
this.setState({
puppyImage: imageUrl
})
} catch (error) {
console.log(error);
}
}
}
在你做一些改变的假设下this.state.breed
。componentDidUpdate()
上面定义的逻辑将触发,然后检查它们是否是先前品种状态和更新品种状态之间的差异。如果存在,则对该品种进行新的访存调用,您将获得一个新的uppyImage :)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句