将对象从API存储到状态

问题描述 投票:0回答:2

我正在尝试使用ReactJS来存储后端API提供的信息。我的后端API返回了一个JSON对象,其中包含:

"a": 123
"b": 345
"c": 0

以上对象从我的后端API存储在data下。

所以现在我想将这些值分别存储在data中的React State中,如下所示:

this.state = {
first:'',
second: '',
third: '',
}

//ComponentDidMount happen here
.then(result => {
        first: //result.data.data value "a":123 will be stored to State *First*
        //and "b":345 will go to second and "c":0 to third
        }
        debugger;
      })

我该为存储要说明的信息该写什么?

javascript reactjs
2个回答
1
投票

您可以尝试

//ComponentDidMount happen here
.then(result => {
    first.setState(result.data.data.a);
    second.setState(result.data.data.b);
    third.setState(result.data.data.c);
}
debugger;
})

2
投票

如果您适合使用0, 1, 2而不是'first', 'second', 'third',则可以映射对象的值,并为每个索引将其存储为状态


  .then(result => Object.values(result).map((value, i) => this.setState({ [i]: value })))
© www.soinside.com 2019 - 2024. All rights reserved.