Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - React状态未更新,尝试使用ES6语法(React state is not updating, trying to use ES6 syntax)

Why is the state not updating?(为什么状态没有更新?)

I have checked that i receive data from the api in the correct form.(我已经检查过我是否以正确的形式从api接收了数据。) I can print the result if i change it instead of trying to add it to a new array and put it in the state.(如果可以更改结果,则可以打印结果,而不是尝试将其添加到新数组并将其置于状态。) I have also checked that this exists in the scope and as I understand it should work since I am using an arrow function.(我还检查了该范围是否存在,并且据我所知它应该可以正常工作,因为我正在使用箭头功能。) I still receive an empty array after the map function.(map函数之后,我仍然收到一个空数组。) What am I missing?(我想念什么?) 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]} )) }   ask by daniel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]} }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...