Home > Web Front-end > Front-end Q&A > How to modify attribute values ​​in react

How to modify attribute values ​​in react

藏色散人
Release: 2022-12-29 09:23:45
Original
2796 people have browsed it

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.

How to modify attribute values ​​in react

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 
})
Copy after login

The implementation of Vue is as follows

this.todoList = response.data;
Copy after login

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: "小候",
      },
    ]
  };
Copy after login

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");
Copy after login

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
    })
Copy after login

It doesn’t work, our editor and browser are reporting errors, telling us that we can’t write like this

How to modify attribute values ​​in react

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)
    });
Copy after login

This is the description of setState on the official website

How to modify attribute values ​​in react

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template