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
166 views
in Technique[技术] by (71.8m points)

javascript - Why setState not set appending my array into state?

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("
").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"]
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

setState is asynchronous. That means it doesn't happen right away, but a very short time later instead. If you add a:

console.log(linkList)

to the top of your render method, you will see the items being appended just as you expect.


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

...