[英]REACT how to store an Object instead of an Array of Objects in setState?
我设置了一个CodeSandbox
基本上,我得到这个:
currencies: [{MXN: "10"},{USD: "10"},{GBP: "10"}]
我正在寻找这个:
currencies: {MXN: "10", USD: "10", GBP: "10"}
为方便阅读而缩短了时间,您可以在CodeSandbox中尝试一下,只需检查控制台是否已准备就绪。
像这样的东西:
currencies = {MXN: this.state.axiosCurrencies[0].value,
USD: this.state.axiosCurrencies[1].value,
GBP: this.state.axiosCurrencies[2].value}
axiosCurrencies状态应包含键名和值,以根据需要生成对象。 因此,请按照以下代码中的说明保留您的USD,GBP等。
做下面的事情
//keep your currencies as an object in state
constructor(props){
this.state = {
currencies: {},
// you need to construct your data axiosCurrencies like below
axiosCurrencies: [{“id”: “01”, “name”: “MXN”, “value”: “abc”}, {“id”: “02”, “name”: “USD”, “value”: “xyz”}, {“id”: “03”, “name”: “GBP”, “value”: “def”}]
}
}
//you can do below iteration in either componentDidMount or componentWillReceiveProps. Use componentWillReceiveProps if you are not using react v16.3 or greater version because this method is deprecated in latest versions.
//do something like below to construct an object as you need.
const obj = {};
const { axiosCurrencies } = this.state;
axiosCurrencies.forEach((item, index) => {
obj[item.name] = item.value;
});
this.setState({
currencies: obj
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.