我遇到以下问题:我编写了一个“detailview”组件,该组件从列表中获取 PK 并使用它从 API 中获取正确的对象。由于这需要一些时间,默认情况下会显示“正在加载”。
我的渲染如下所示:
render() {
if (!this.store_item) {
return <h2>loading</h2>
}
return(
<div>
<h2>{this.state.store_item.results.title}</h2>
<p>{this.state.store_item.results.description}</p>
</div>
)
}
组件安装时会加载“store_item”:
componentDidMount() {
this.LoadApi();
}
“LoadApi”方法具有以下代码:
LoadApi() {
const new_url = encodeURI(this.state.store_item_api + this.props.detail_pk);
fetch(new_url, {
credentials: 'include',
})
.then(res => res.json())
.then(result =>
this.setState({
store_item: result,
}));
}
但是,当我在浏览器中运行此代码时,我看到的只是“正在加载”。然而,当我检查 chromium React 扩展中的状态时,我可以看到“store_item”已设置(我还验证了 api 调用是否按网络选项卡中的计划进行)。由于状态已设置(并且正在“LoadApi”中设置),我的理解是这应该触发重新渲染。
有谁知道为什么尽管如此,组件仍然返回“正在加载”?
最佳答案
您有拼写错误,错过了state
关键字
if (!this.store_item) { ... }
^^^^^^^^^^^^^^^^^^
应该是
if (!this.state.store_item) { ... }
因为它被定义为组件状态而不是组件静态属性。
关于reactjs - react : Component wont reload - even though new state has been set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48167200/