React Item.map 不是函数

我正在尝试为状态数组 personState 中的值实现名称更改处理程序。


const [personState, setPersonState] = useState([

            { id:'asdasd', name: "Max", age: 28 },

            { id:'asdasdsd', name: "Manu", age: 29 },

            { id:'assddasd', name: "Stan", age: 31 },

  ]);

这是处理名称更改事件的函数:


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

    }

下面是我在切换显示时使用 map 遍历 personState 数组的地方。用于显示数据和删除数据的映射工作但是当我想实现名称更改时,它突然返回:


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>

任何帮助将非常感激


开心每一天1111
浏览 94回答 1
1回答

撒科打诨

这是罪魁祸首:setPersonState(...personState,&nbsp;persons);//set&nbsp;state&nbsp;with&nbsp;the&nbsp;new&nbsp;array它应该被新值替换(只有一个参数)setPersonState(persons);//set&nbsp;state&nbsp;with&nbsp;the&nbsp;new&nbsp;array
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript