reactjs - 重新渲染兄弟组件后在父组件中渲染子组件
问题描述
我有一个父组件,其中包含两个子组件(AddPersonForm 和 PeopleList)。当我通过 AddPersonForm 提交名称时,我希望它在 PeopleList 组件中呈现,但事实并非如此。
这是我的AddPersonForm:
class AddPersonForm extends React.Component {
state = {
person: ""
}
handleChange = (e) => this.setState({person: e.target.value});
handleSubmit = (e) => {
if(this.state.person != '') {
this.props.parentMethod(this.state.person);
this.setState({person: ""});
}
e.preventDefault();
}
render() {
return (
<form onSubmit={this. handleSubmit}>
<input type="text" placeholder="Add new contact" onChange={this.handleChange} value={this.state.person} />
<button type="submit">Add</button>
</form>
);
}
我的PeopleList组件:
class PeopleList extends React.Component {
constructor(props) {
super(props);
const arr = this.props.data;
this.state = {
listItems: arr.map((val, index) => <li key={index}>{val}</li> );
}
}
render() {
return <ul>{this.state.listItems}</ul>;
}
}
现在是父组件ContactManager:
class ContactManager extends React.Component {
state = {
contacts: this.props.data
}
addPerson = (name) => {
this.setState({contacts: [... this.state.contacts, name]});
render() {
return (
<div>
<AddPersonForm parentMethod={this. addPerson}×/>
<PeopleList data={this.state.contacts} />
</div>
);
请问我做错了什么,或者没有做什么?
解决方案
您PeopleList
在创建和安装道具时使用道具进行初始化,但是您没有使用道具的新值来更新它。
要解决您的问题,请在渲染时使用 prop 的当前值:
class PeopleList extends React.Component {
render() {
return <ul>{ this.props.data.map((val, index) => <li key={index}>{val}</li>) }</ul>;
}
}
推荐阅读
- elasticsearch - 具有多个字段的 Elasticsearch 等效 SQL In Query
- javascript - react-native-document-picker 应用程序在文档选择后关闭/崩溃
- java - 空手道:打印语句不使用 log4j2 写入控制台
- asp.net - Blazor Server:如何“监视文件更改”和“附加到 Visual Studio”
- rest - Odoo 中的 Odoo RPC、Xml RPC、JSON RPC 和 REST API 有什么区别?
- firebase - 参数类型“int”不能分配给参数类型“List”
'。使用 FieldValue.arrayUnion Firestore Flutter 时出错 - react-native - React Native将数据插入嵌套数组
- reactjs - 表单提交反应js时preventDefault不起作用
- java - 在 Java 中将方法作为参数传递给另一个方法是不好的做法吗?
- r - 有没有办法从 R 编写一个带有系数、se、p、优势比和 CI 的回归表?