简体   繁体   中英

react not updating array state

if I clicked the button to update name then it's not changing using setState I want update persons variable and as well it should update in the DOM.

Please suggest me idea how to update the state

App.js

import React, { Component } from "react";
import Person from "./component/Person";
import "./App.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      persons: [
        { name: "max", age: 28 },
        { name: "manu", age: 29 },
        { name: "step", age: 26 }
      ]
    };
  }

  chnagenames = () => {
    console.log("clicked me ");
    this.setState = {
      persons: [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ]
    };
    console.log(this.state.persons);
  };

  render() {
    return <> {/* ... */} </>;
  }
}

export default App;

Person.js

import React from "react";

const Person = props => {
  return (
    <>
      person age is {props.ages} and name is {props.attrib}{" "}
    </>
  );
};

export default Person;

You should call this.setState as it is a function, not assign a new value to it.

You also have a typo on the chnagenames method, and setState is also asynchronous so you will not see the change if you log it directly after setState .

changenames = () => {
  console.log("clicked me ");
  this.setState(
    {
      persons: [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ]
    },
    () => console.log(this.state.persons)
  );
};

please try this :

chnagenames = () => {
    console.log("clicked me ");
    var changedArray = [
        { name: "maxi", age: 28 },
        { name: "manr", age: 29 },
        { name: "step", age: 27 }
      ];

    this.setState({
      persons: changedArray
    }, function {
      console.log(this.state.persons);});    
  };

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