为什么setState不设置将我的数组追加到状态? [英] Why setState not set appending my array into state?

查看:47
本文介绍了为什么setState不设置将我的数组追加到状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个包含多个链接的文本区域,然后将 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 reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

这篇关于为什么setState不设置将我的数组追加到状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆