首页 > 解决方案 > SetState 空数组与对象的 Json 响应数组?

问题描述

我已将数组的状态设置为 [] 空,在 componentDidMount 中我正在获取 API 响应。现在我想用新的 json 响应数组设置空数组的状态我该怎么做?

constructor(props)
{
    super(props)
    this.state = {
        categoryList : []
    }
}
componentDidMount()
{

    axios.get('http:xxxxxxxxxxxxxxxxxxxxxxx')

    .then(res => 
    {
        this.setState = {
            categoryList : res.data.body.category_list(json path)
        }
    })
    .catch(function(error) {
        console.log('Error on Authentication' + error);
    })
}

标签: reactjs

解决方案


尝试这个:

 this.setState({
    categoryList : res.data.body.category_list(json path)
 })

因为setState()方法接受将与当前状态合并的对象。


推荐阅读