The problem is that you are using [...this.state.currencies, currency.id]
.(问题是您正在使用[...this.state.currencies, currency.id]
。)
Since setState
is also async, the state does not change for each iteration of the map.(由于setState
也是异步的,因此状态不会在映射的每次迭代中更改。) So you are always using the same this.state.currencies
.(因此,您始终使用相同的this.state.currencies
。) This means that you should only get the last currency.id
added.(这意味着您应该只添加最后一个currency.id
。)
You should either use the function version of setState
(您应该使用setState
的函数版本)
this.setState((state) => ({currencies: [...state.currencies,currency.id]}));
or simply do the map
and use the resulting array to set the state(或者只是做map
并使用结果数组设置状态)
fetchCurrencies = async () => {
const response = await axios.get('some address');
const currencyIds = response.data.map(currency=>currency.id);
this.setState({currencies: [...this.state.currencies,...currencyIds]}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…