React 组件渲染和fetch请求数据前后问题

我想通过fetch请求服务端数据,然后在渲染组件,但是fetch返回的是promise,这个是异步的所以在数据没有准备好的前提下我的组件已经渲染了,所以如何让我的数据准备好之后再渲染组件!

clipboard.png

clipboard.png

阅读 7.2k
3 个回答

{

this.state.blogList.length != 0 && (
    <div className="blog_cas">...</div>
)

}
或者
if (this.state.blogList.length = 0) return null
是这个意思吗?

blogList只获取数据,写一个专用的渲染方法渲染数据,如下:

class ...


    componentWillMount() {
        fetch().then().then((jsonData) => {
            this.setState({
                blogList: jsonData
            })
        })
    }
    ..
    
    
    renderBlogList(list) {
        //渲染过程
    }
    
    render () {
        return <div>
            {this.state.blogList && this.renderBlogList(this.state.blogList)}
        </div>
    }

    

补充: 如果你要用blogList渲染,blogList应该是这种格式吧:

this.setState({
    blogList: (
    <ul>
        <li>1</li>
        <li>2</li>
    </ul>)
})

给你个思路,添加一个状态 loading,在加载数据前把 loading 设 true,渲染加载特效(或者干脆什么都不渲染),数据加载完毕后把 loading 设 false,渲染你的最贱。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题