React状态未更新,尝试使用ES6语法

dan*_*iel 1 javascript ecmascript-6 reactjs axios

为什么状态没有更新?我已经检查过我是否以正确的形式从api接收了数据。如果可以更改结果,则可以打印结果,而不是尝试将其添加到新数组并将其置于状态。我还检查了该范围是否存在,并且据我所知它应该可以工作,因为我使用的是箭头功能。map函数之后,我仍然收到一个空数组。

我想念什么?

class CurrencyForm extends React.Component {
  state = {
    currencies: [],
  }
  componentDidMount(){
   this.fetchCurrencies();
  }

  fetchCurrencies = async () => {
    const response = await axios.get('some address')
    response.data.map(currency => 
    this.setState({currencies: [...this.state.currencies,currency.id]}
    ))
   }
Run Code Online (Sandbox Code Playgroud)

Gab*_*oli 5

问题是您正在使用[...this.state.currencies, currency.id]

由于setState也是异步的,因此状态不会随着地图的每次迭代而更改。所以你总是使用相同的this.state.currencies。这意味着您应该只currency.id添加最后一个。

您应该使用的功能版本 setState

this.setState((state) => ({currencies: [...state.currencies,currency.id]}));
Run Code Online (Sandbox Code Playgroud)

或干脆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]}
}
Run Code Online (Sandbox Code Playgroud)