简体   繁体   中英

React Item.map is not a function

I'm trying to implement a name change handler for a value in state array personState.

const [personState, setPersonState] = useState([
            { id:'asdasd', name: "Max", age: 28 },
            { id:'asdasdsd', name: "Manu", age: 29 },
            { id:'assddasd', name: "Stan", age: 31 },
  ]);

Here's the function for handling name change event:

const nameChangeHandler = (event, id) => {
        const personIndex = personState.findIndex(p => {
            return p.id === id;//find index of the value in personstate with id equal id passed in
        })
        const person = {...personState[personIndex]} // get all the object value inside that person

        person.name = event.target.value; //change name of that copy person to the input value

        const persons = [...personState]; //copy array of current personState
        persons[personIndex] = person// change value of that person in the array
        setPersonState(...personState, persons);//set state with the new array
    }

down below is where I use map to iterate through the personState array if the toggle show up. The mapping work for showing the data as well as deleting the data but when I want to implement name change, it suddenly return:

TypeError: personState.map is not a function
App
D:/React App/react-guide/src/App.js:52
  49 |  <button onClick={() => togglePersonHandler()}>
  50 |      Switch Name
  51 |  </button>
> 52 |  {showPerson ? personState.map((person,index) => {
  53 |       return <Person click = {()=>deletePersonHandler(index)} changed={(event) => nameChangeHandler(event, person.id)} key={person.id} name={person.name} age ={person.age}/>
  54 |     }) : null}
  55 | </div>

Any help would be much appreciated

This is the culprit:

setPersonState(...personState, persons);//set state with the new array

It should be replaced by the new value (only one parameter)

setPersonState(persons);//set state with the new array

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