Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...