How to modify attribute values in react: 1. Open the corresponding code file; 2. Create the array object; 3. Pass "this.setState({todoList: todoList.map((item,key)=> ;key == 0?{...item,name: "Jony"}:item)});" method can modify a certain attribute value in the array object.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to modify attribute values in react?
React modifies a certain attribute value in the array object
Generally, we will process the data in the Controller and send it to the View. ) layer for display, this simple assignment method is as follows
this.setSate({ toList: response.data })
The implementation of Vue is as follows
this.todoList = response.data;
For example, this is the data passed to us by the background,
We want to change How to implement the value of one of the `name` attributes of the array object?
state = {//类似于Vue里面的data() todoList: [ { img: "xxx", name: "小飞", }, { img: "xxx", name: "小候", }, ] };
Let’s first take a look at how to implement it in vue
this.todoList[0].name = "Jony"; //或者 this.$set(this.todoList[0],"name","Jony");
Wow~ It’s actually relatively simple, so how to implement it in React?
Imagination is like this...
this.setState({ todoList[0].name:"Jony" }) //这样报错了,立马想到另一种方式 let obj = { img:"xxx", name:"Jony" } this.setState({ todoList[0]:obj })
It doesn’t work, our editor and browser are reporting errors, telling us that we can’t write like this
So how to implement it
//三目运算符 `key == 0` 是我写死的 //如果是点击传入的话可以是`key == index(下标)` const todoList = [...this.state.todoList]; //浅拷贝一下 this.setState({ todoList: todoList.map((item,key)=>key == 0?{...item,name: "Jony"}:item) });
This is the description of setState on the official website
Recommended learning: "react video Tutorial》
The above is the detailed content of How to modify attribute values in react. For more information, please follow other related articles on the PHP Chinese website!