为什么setState不设置将我的数组追加到状态? [英] Why setState not set appending my array into state?
问题描述
我必须创建一个包含多个链接的文本区域,然后将 split()
放入数组yeah,它的工作正常,但我想将该数组设置为我的 state
在 linkList:[]
中,但是当我单击提交按钮时,它在初始化时为我提供了一个空数组.但是当我再次按下提交按钮时,它会给我我想要的列表,为什么?这是代码和输出
I have to create a text area which taken multiple links then I split()
into array yeah Its working fine, but I want to set that array into my state
in linkList: []
but when I click to button for submitting it gives me empty array as I initialize. but when I again press to submit button then it gives me my desired list, why? here are code and outputs
onSubmit = event => {
this.setState({ loading: true, host: undefined });
const { text, linkList } = this.state;
console.log(text);
const mList = text.split("\n").filter(String);
console.log(mList);
this.setState({
linkList: [...mList]
});
console.log(linkList);
event.preventDefault();
};
输出控制台(首次点击)
Output console (First Click)
youtube.com
google.com
facebook.com
------------------------------------------------------------
["youtube.com", "google.com", "facebook.com"]
------------------------------------------------------------
[]
输出控制台(第二次点击)
Output Console (Second Click)
youtube.com
google.com
facebook.com
---------------------------------------------
["youtube.com", "google.com", "facebook.com"]
---------------------------------------------
["youtube.com", "google.com", "facebook.com"]
推荐答案
它可能正在附加,直到下一次渲染才可用.
It probably is being appended, it's just not available until the next render.
从文档:
setState()
并不总是立即更新组件.它可能会批量更新或将更新推迟到以后.这使得在调用setState()
后立即读取this.state
是潜在的陷阱.相反,请使用componentDidUpdate
或setState
回调(setState(updater,callback)
),这两种更新均可以在更新完成后触发已应用.
setState()
does not always immediately update the component. It may batch or defer the update until later. This makes readingthis.state
right after callingsetState()
a potential pitfall. Instead, usecomponentDidUpdate
or asetState
callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied.
这篇关于为什么setState不设置将我的数组追加到状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!