reactjs - react : Component wont reload - even though new state has been set

标签 reactjs

我遇到以下问题:我编写了一个“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/

相关文章:

javascript - 我为状态创建了一个通用的 reducer ,什么时候应该使用它什么时候不应该使用它

javascript - 遍历 JSON 时 react 极慢

javascript - 如何在不渲染组件的情况下传递 Prop ?

javascript - 使用 ReactJS 和 fetch-api 访问和显示 JSON 时遇到问题

css - 如何配置 Create React App 以使用 CSS block ?

javascript - 使用 React onClick() 时更改颜色

reactjs - 使用 Flow Typings react useRef Hook

javascript - react 中的 firebase 导出问题

javascript - 如何使用 Vite 中构建的 React 将文件夹中的所有图像导入数组?

javascript - 语义用户界面( react ): Responsive vertical menu by changing to horizontal on mobile devices