Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应:组件不会重新加载-即使已设置新状态_Reactjs - Fatal编程技术网

Reactjs 反应:组件不会重新加载-即使已设置新状态

Reactjs 反应:组件不会重新加载-即使已设置新状态,reactjs,Reactjs,我有以下问题:我编写了一个“detailview”组件,它从列表中获取一个PK,并使用它从API中获取正确的对象。由于这需要一些时间,因此默认情况下将显示“加载” 我的渲染如下所示: render() { if (!this.store_item) { return <h2>loading</h2> } return( <div>

我有以下问题:我编写了一个“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>
        )
    }
“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”中设置),我的理解是这应该触发重新渲染

有人知道为什么尽管如此,组件仍不断返回“加载”吗?

您输入了拼写错误,遗漏了
状态
关键字

应该是

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


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

啊,这是一个愚蠢的错误。看来我需要更多的咖啡。谢谢你的帮助!调试状态或属性更改时最简单的方法是在
render()中的return语句之前执行
console.log(this)
。这通常会给我一个很好的线索去哪里找
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,
                }));
    }
if (!this.store_item) { ... }
   ^^^^^^^^^^^^^^^^^^