Why does the state not show the newly created empty object? Workaround Found

I use reaction 16.3.0-alpha.1 and have a problem adding an empty object with key "elements" to the list object.

Addlist.js

createList = event => {
    //Stop form from submitting
    event.preventDefault();

   const list = {
       items: {},
       title: this.titleRef.current.value
   };
   this.props.addList(list); //This method lives in app.js

   // Clear the form after submitted
   event.currentTarget.reset();
};

App.js

state = {
    lists: {}
};

//Add new list with title and empty items object
addList = list => {

    // Take a copy of current state
    const lists = { ...this.state.lists };

    // Add new list to the lists collection
    lists[`${list.title}`] = list;

    console.log(lists);

    // Set the new lists collection to state
    this.setState({ lists: lists });
};

When the createList event occurs, it calls the addList method on app.js and passes the list object to the method. When I mount the log lists right before setState, I see that "list3" has been added with "elements" and "heading". But when I used the dev tools to view the state, it only displays the "title" key with its value. I also get an error message indicating that the key "items" in "list3" are null or undefined.

console.log

state

? setState, - ?


, , , .

list.items = {} list.items = ". . , " list.items ", , . , " list.items" . . setState.

, , .

+4

Source: https://habr.com/ru/post/1695379/


All Articles