setState is not updating state properly

后端 未结 4 1954
忘掉有多难
忘掉有多难 2021-01-21 09:31

Sorry, I really miss something with the transmission of state within props of sub components in React.

I have implemented a version of a todo l

4条回答
  •  清歌不尽
    2021-01-21 10:18

    As per MDN DOC:

    The push() method adds one or more elements to the end of an array and returns the new length of the array.

    Array.push never returns the result array, it returns the number, so after adding the first task, this.state.tasks becomes a number, and it is throwing the error when you trying to run map on number.

    You did the mistake here:

    addTask(task) {
        this.setState({
            tasks: this.state.tasks.push(task)
        })
    }
    

    Write it like this:

    addTask(task) {
        this.setState( prevState => ({
            tasks: [...prevState.tasks, task]
        }))
    }
    

    Another import thing here is, the new state will be depend on the previous state value, so instead of using this.state inside setState, use updater function.

    Explanation about Edit part:

    Two important things are happening there:

    1- setState is async so just after setState we can expect the updated state value.

    Check this for more details about async behaviour of setState.

    2- Array.push always mutate the original array by pushing the item into that, so you are directly mutating the state value by this.state.tasks.push().


    Check the DOC for more details about setState.

    Check the MDN Doc for spread operator (...).

    Check this snippet:

    let a = [1,2,3,4];
    
    let b = a.push(5);  //it will be a number
    
    console.log('a = ', a);
    
    console.log('b = ', b);

提交回复
热议问题