[英]React state is not updating, trying to use ES6 syntax
为什么状态不更新? 我已经检查过我是否以正确的形式从 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]}
))
}
问题是您正在使用[...this.state.currencies, currency.id]
。
由于setState
也是异步的,因此地图的每次迭代的状态都不会改变。 所以你总是使用相同的this.state.currencies
。 这意味着您应该只添加最后一个currency.id
。
您应该使用setState
的函数版本
this.setState((state) => ({currencies: [...state.currencies,currency.id]}));
或者只是做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]}
}
如果你想把所有的 id 放在 state 中......而不是多次调用setState
,你可以先把所有的 id 放在一个数组中,然后用这个数组更新状态,如下所示:
fetchCurrencies = async () => {
const response = await axios.get('some address')
const idsArray = response.data.map(currency => currency.id)
this.setState({currencies: idsArray})
}
并记住 setState 是一个异步调用,因此如果将console.log
放在setState
之后,您可能无法看到结果,而是尝试在渲染方法中进行控制台日志记录
如果要在类组件上使用状态,则必须使用构造器方法
class CurrencyForm extends React.Component { constructor () { super() 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]} )) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.