React详情组件已设置store_item状态却仍显示Loading,无法重渲染
问题分析与解决方案
嘿,我一眼就抓到问题的核心了——你在render方法里判断的是this.store_item,但实际上你把API返回的数据存在了组件的state里,也就是this.state.store_item!
核心错误点
你的render逻辑里写的是:
if (!this.store_item) { return <h2>loading</h2> }
但你在LoadApi里是通过this.setState({ store_item: result })把数据放到state中的,this.store_item这个变量根本没被定义过,所以它永远是undefined,导致你的判断永远为真,页面就一直卡在loading状态。
修正后的代码
把render方法里的判断改成检查state里的store_item就可以了:
render() { // 这里改成判断state中的store_item if (!this.state.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> ) }
额外优化建议
为了避免API返回结构异常(比如results字段不存在)导致页面报错,你可以加上可选链操作符做一层兜底:
<h2>{this.state.store_item?.results?.title || '暂无标题'}</h2> <p>{this.state.store_item?.results?.description || '暂无描述'}</p>
这样即使数据返回不符合预期,页面也能正常显示兜底内容,不会直接崩溃。
内容的提问来源于stack exchange,提问作者Jasper
相关产品推荐
相关产品推荐

