【问题标题】:SetState the empty array with Json Response array of object?SetState 空数组与对象的 Json 响应数组?
【发布时间】:2018-09-28 07:46:47
【问题描述】:

我已将数组的状态设置为 [] 空,在 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);
    })
}

【问题讨论】:

  • 以上代码有什么问题。
  • 我想将 categoryList 的状态设置为 Api Json 响应.. 只想用 json 响应更新空数组..
  • setState是一个方法,需要用object/updater函数调用,去掉=,像这样:this.setState({ categoryList : res.data.body.category_list(json path) })
  • 哎哟...对不起,我没有正确检查代码...谢谢你

标签: reactjs


【解决方案1】:

试试这个:

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

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

【讨论】:

【解决方案2】:

这里你需要了解两件事

以下功能用于使用初始值初始化状态

this.state = {
  categoryList: []
}

要修改 categoryList 状态或任何其他状态变量,您需要使用 setState 方法,如下所示。请记住 setState 是一种方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多