首页 > 解决方案 > 重新渲染兄弟组件后在父组件中渲染子组件

问题描述

我有一个父组件,其中包含两个子组件(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>
     );

请问我做错了什么,或者没有做什么?

标签: reactjsreact-component

解决方案


PeopleList在创建和安装道具时使用道具进行初始化,但是您没有使用道具的新值​​来更新它。

要解决您的问题,请在渲染时使用 prop 的当前值:

class PeopleList extends React.Component {
   render() {
      return <ul>{ this.props.data.map((val, index) => <li key={index}>{val}</li>) }</ul>;
   } 
}

推荐阅读