REACT 如何在 setState 中存储对象而不是对象数组?
REACT how to store an Object instead of an Array of Objects in setState?
- 我正在尝试将数据存储为一个对象,并且我得到了一个对象数组,我试图在不改变原始状态对象的情况下执行此操作,这是一个实际的对象数组,这是我的前端逻辑如果我有一个简单的 Object(dict).
我设置了一个CodeSandbox
基本上,我得到这个:
currencies: [{MXN: "10"},{USD: "10"},{GBP: "10"}]
我正在寻找这个:
currencies: {MXN: "10", USD: "10", GBP: "10"}
为方便阅读而缩短,您可以在 CodeSandbox 中试用,只需检查控制台是否已准备就绪。
- 如果有一种已知的方法可以避免创建新状态而只使用第一个状态,请告诉我如何操作或在哪里可以阅读它,我仍在学习 React。我试图在 class 中创建一个 属性 以将值存储在那里,但我想我不明白它是如何工作的。
有点像这样:
currencies = {MXN: this.state.axiosCurrencies[0].value,
USD: this.state.axiosCurrencies[1].value,
GBP: this.state.axiosCurrencies[2].value}
axiosCurrencies 状态应包含键名和值,以根据需要生成对象。
所以请按照下面的代码保留您的美元、英镑等。
做如下的事情
//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
});
- 我正在尝试将数据存储为一个对象,并且我得到了一个对象数组,我试图在不改变原始状态对象的情况下执行此操作,这是一个实际的对象数组,这是我的前端逻辑如果我有一个简单的 Object(dict).
我设置了一个CodeSandbox
基本上,我得到这个:
currencies: [{MXN: "10"},{USD: "10"},{GBP: "10"}]
我正在寻找这个:
currencies: {MXN: "10", USD: "10", GBP: "10"}
为方便阅读而缩短,您可以在 CodeSandbox 中试用,只需检查控制台是否已准备就绪。
- 如果有一种已知的方法可以避免创建新状态而只使用第一个状态,请告诉我如何操作或在哪里可以阅读它,我仍在学习 React。我试图在 class 中创建一个 属性 以将值存储在那里,但我想我不明白它是如何工作的。
有点像这样:
currencies = {MXN: this.state.axiosCurrencies[0].value,
USD: this.state.axiosCurrencies[1].value,
GBP: this.state.axiosCurrencies[2].value}
axiosCurrencies 状态应包含键名和值,以根据需要生成对象。 所以请按照下面的代码保留您的美元、英镑等。
做如下的事情
//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
});