React: Updating state when state is an array of objects

后端 未结 2 1479
盖世英雄少女心
盖世英雄少女心 2020-12-04 20:14

I have an array of objects in state:

this.state = {
  items: [
    {id: 1, someattr: \"a string\", anotherattr: \"\"},
    {id: 2, someattr: \"another string         


        
2条回答
  •  时光说笑
    2020-12-04 20:55

    Your update function would look like this

    updateItem(id, itemAttributes) {
      var index = this.state.items.findIndex(x=> x.id === id);
      if (index === -1)
        // handle error
      else
        this.setState({
          items: [
             ...this.state.items.slice(0,index),
             Object.assign({}, this.state.items[index], itemAttributes),
             ...this.state.items.slice(index+1)
          ]
        });
    }
    

    And you use it like this

    this.updateItem(2, {someattr: 'a new value'});
    

    Gross right?


    You're going to have a big headache in general if you continue to build a complex application in this manner. I would recommend you look into redux or some other Flux implementation that is better suited for solving these problems.

    Redux uses a concept of state reducers which each work on a specific slice of the state of your application. That way you don't have to manually dig through your entire state each time you want to affect a deep change.

    The creator of Redux, Dan Abramov, has made two video courses available online for free. Dan is an excellent teacher and I felt comfortable with the Redux pattern after spending just one afternoon with it.

    • https://egghead.io/courses/getting-started-with-redux
    • https://egghead.io/courses/building-react-applications-with-idiomatic-redux

提交回复
热议问题