我正在学习反应。我只想测试带有钩子的数组的双重绑定,所以我创建了一个表,并用它和输入修改了在状态中设置的对象的属性。设置状态后,我得到了无法读取的“未定义”属性“地图”。
我比较原始对象和新对象,它们都具有相同的结构
//For App.js
import React, { useState } from 'react';
import Person from './Person/Person'
import './App.css';
const App = props => {
const [peopleState, setPeopleState] = useState({
people: [{ id: "001", name: "John Smith", address: "Main AV", phone: "312312" },
{ id: "002", name: "Marc Muller", address: "Second AV", phone: "345435" },
{ id: "003", name: "Sam Lopez", address: "Thrid AV", phone: "456444" },
{ id: "004", name: "Peter McNiece", address: "Road AV", phone: "213456" }]
});
const changeHandler = (event, index) => {
//This should be changed by using a copy
console.log(JSON.stringify(peopleState))
const newList = peopleState;
const newObj = peopleState.people[index];
newObj.name = event.target.value;
newList.people[index] = newObj;
setPeopleState({ newList })
console.log(JSON.stringify(peopleState))
}
let listOfPeople = null;
listOfPeople = (
<div>
{
peopleState.people.map((p, index) => {
return <Person name={p.name} address={p.address} phone={p.phone}
changed={(event) => changeHandler(event, index)} />
})}
</div>)
return (
<div>
<h1>Example</h1>
{listOfPeople}
</div>
);
}
export default App;
//For Person.js
import React from 'react';
import './Person.css';
const person = (props)=>{
return(
<div className="Person">
<table>
<tr>
<td>{props.name}</td>
<td>{props.address}</td>
<td>{props.phone}</td>
<td><input type="text" onChange={props.changed} value={props.name} /></td>
</tr>
</table>
</div>
);
}
export default person;
顺便说一句,如果我要进行更新,是否必须克隆状态对象?
答案 0 :(得分:0)
您可以像这样完成双重装订的外观
如果您想在操作中看到它,这里也是沙箱:https://codesandbox.io/s/7345kyly21
import React, { useState, useEffect } from "react";
import Person from "./Person";
import ReactDOM from "react-dom";
const App = props => {
const [peopleState, setPeopleState] = useState({
people: [
{ id: "001", name: "John Smith", address: "Main AV", phone: "312312" },
{ id: "002", name: "Marc Muller", address: "Second AV", phone: "345435" },
{ id: "003", name: "Sam Lopez", address: "Thrid AV", phone: "456444" },
{ id: "004", name: "Peter McNiece", address: "Road AV", phone: "213456" }
]
});
const changeHandler = (event, index) => {
const newList = peopleState.people.map((person, pIndex, array) => {
if (index === pIndex) {
return {
...person,
name: event.target.value
};
} else {
return person;
}
});
setPeopleState({ people: newList });
};
useEffect(() => {
console.log(peopleState);
}, [peopleState]);
const renderList = () => {
return (
<div>
{peopleState.people.map((p, index) => {
return (
<Person
name={p.name}
address={p.address}
phone={p.phone}
changed={event => changeHandler(event, index)}
/>
);
})}
</div>
);
};
return (
<div>
<h1>Example</h1>
{renderList()}
</div>
);
};
同样,您会因为以下原因而得到未定义的地图错误:
setPeopleState({ newList })
当您传递这样的参数时,您正在传递新的键值。您的状态变量变为{newList:[arrayofpeople]},并且您仍然尝试在render中映射peopleState.people。 .people
不再是您状态下的键,这就是为什么您不确定的原因。