React:组件不会重新加载 - 即使已经设置了新状态

时间:2018-01-09 11:28:43

标签: 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,
                }));
    }

但是,当我在浏览器中运行此代码时,我看到的只是“正在加载”。然而,当我检查chrome react扩展中的状态时,我可以看到'store_item'已经设置(我还验证了api调用在网络选项卡中按计划进行)。由于状态已设置(并且正在“LoadApi”中设置),我的理解是这应该触发重新渲染。

有没有人知道为什么,尽管如此,该组件仍然会继续“加载”?

1 个答案:

答案 0 :(得分:3)

您输错了,错过了 state 关键字

if (!this.store_item) { ... }
   ^^^^^^^^^^^^^^^^^^

应该是

if (!this.state.store_item) { ... }

因为它被定义为组件状态而不是组件静态属性。