简体   繁体   中英

update doesn't work with setState in react

Try to update a state of array using map of es6, got some issue.. What's wrong with this code?

this.setState({
  drinks: this.state.drinks.map(o => {
    if (o === this.state.newDrink) {
      return this.state.newDrink;
    }
    return o;
  })
});

where drinks is an array. My add functionality is fine but not for update, I think something is wrong above?

My demo https://codesandbox.io/s/nk6qo8krvm

Try this solution, it may help.

const drinks = this.state.drinks
drinks.map((data) => {
  if (data === this.state.newDrink){
    this.setState({drinks: this.state.newDrink})
  } else {
    this.setState({drinks: data})
  }
})

You are comparing your newdrink with the old drink.

For example if you edit coffee and make it coffeef you compare in the map function coffee with coffeef . So it wouldn't change anything.

You should safe a reference of the old value so you can compare it with that.

state = {
    drinks: ["coffee", "milo", "plain water"],
    modalIsOpen: false,
    newDrink: "",
    oldDrink: "" // <-- added
};

handleOpenModal = (isEdit, existingDrink) =>
    this.setState({
        modalIsOpen: true,
        newDrink: existingDrink,
        oldDrink: existingDrink, // <-- added
        isEdit
    });

this.setState({
    drinks: this.state.drinks.map(o => {
        console.log(o)
        console.log(this.state.newDrink)
        if (o === this.state.oldDrink) { // <-- changed
            return this.state.newDrink;
        }
        return o;
    }),
    modalIsOpen: false,
    newDrink: ""
});

Working example: https://codesandbox.io/s/5k2y2l341k

Warning

Because you compare the drink names. If you have 2 drinks that are the same name it will change both the values when you change one.

Edit

Like @Tho Vu pointed out. You could use the index instead of the name to compare. That's a way better solution and it fixes the above problem.

https://codesandbox.io/s/w76978l6mw

The issue is basically your comparison in the map. Try and console log your map function and you can see the array never changes.

The if statement checks if there is any existing values in the list that are equal to the newDrink value, if there is return the newDrink value.

Clearly, your list will never update, as the newDrink value is different than the existing values.

There is a lot of other problems with your code, however I have resolved your issue in your existing snippet: https://codesandbox.io/s/10qpxx2nwj

This solution is slightly faster than mapping over the entire list, as now the code parses in the index of the value you want to change and simply updates the value in the list if you are in "edit mode".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM