下面是我正在处理的代码,click here用于codeandbox链接。
import React from "react";
import ReactDOM from "react-dom";
class PhoneBookForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
phoneNo: ""
};
}
onChange = event => {
this.setState({ [event.target.name]: event.target.value }, () => {
console.log(this.state);
});
};
onSubmit = () => {
console.log("called");
this.props.appendToList({
firstName: this.state.firstName,
lastName: this.state.lastName,
phoneNO: this.state.phoneNo
});
};
render() {
return (
<div>
<label>First Name:</label>
<input type="text" name="firstName" onChange={this.onChange} />
<br />
<label>Last Name:</label>
<input type="text" name="lastName" onChange={this.onChange} />
<br />
<label>Phone Number:</label>
<input type="text" name="phoneNo" onChange={this.onChange} />
<br />
<button onClick={this.onSubmit}>Submit</button> <br />
<br />
</div>
);
}
}
function InformationTable(props) {
console.log("props info", props.peoples);
return (
<table>
<thead>
<th style={{ border: "solid 1px" }}>First Name</th>
<th style={{ border: "solid 1px" }}>Last Name</th>
<th style={{ border: "solid 1px" }}>Phone No</th>
</thead>
{props.peoples.map(person => {
return (
<tr key={person.phoneNo}>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>{person.phoneNo}</td>
</tr>
);
})}
</table>
);
}
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
listOfPeople: [{}]
};
}
appendToList(people) {
console.log("called2");
// let peoples = this.state.listOfPeople.push(people);
console.log("people", people);
this.setState({ listOfPeople: people }, () => {
console.log(this.state.listOfPeople);
});
}
render = () => {
return (
<section>
<PhoneBookForm appendToList={this.appendToList.bind(this)} />
<InformationTable peoples={this.state.listOfPeople} />
</section>
);
};
}
ReactDOM.render(<Application />, document.getElementById("root"));
正如您在上方看到的,每当我尝试单击“提交”按钮时,InformationTable组件都不会呈现。您也可以在codeandbox上尝试一下。一旦您单击该提交按钮,您将在控制台中看到一条错误消息,提示您上述错误发生在InformationTable组件中,并且显示空白页,而不是我的结果寻找。
但是,如果我从组件中删除下面的整行,则它的行为正常
{props.peoples.map(person => {
return (
<tr key={person.phoneNo}>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>{person.phoneNo}</td>
</tr>
);
})}
我还像上面的 console.log(“ props info”,props.peoples); 一样在上面登录了控制台,以验证对象是否有数据。我想我缺少了一个很小的细节,我现在无法弄清。
答案 0 :(得分:2)
这是代码修复
appendToList(people) {
console.log("called2");
// let peoples = this.state.listOfPeople.push(people);
console.log("people", people);
// this.setState(prevState => {
// listOfPeople: prevState.listOfPeople.concat(people);
// });
this.setState({ listOfPeople: this.state.listOfPeople.concat(people) }, () => {
console.log(this.state.listOfPeople);
});
}