Why setState not set appending my array into state?

后端 未结 3 849
别跟我提以往
别跟我提以往 2021-01-27 03:11

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

相关标签:
3条回答
  • 2021-01-27 03:29

    The below code might help.

    onSubmit = event => {
        this.setState({ loading: true, host: undefined }, () => {
          const { text, linkList } = this.state;
    
          console.log(link);
          const mList = text.split("\n").filter(String);
          console.log(mList);
          this.setState({
            linkList: [...mList]
          }, () => {
            console.log(linkList);
            event.preventDefault();
          });
        });
      };
    
    0 讨论(0)
  • 2021-01-27 03:30

    It probably is being appended, it's just not available until the next render.

    From the documentation:

    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.

    0 讨论(0)
  • 2021-01-27 03:32

    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.

    0 讨论(0)
提交回复
热议问题