重新渲染兄弟组件后在父组件中渲染子组件

Render child component in parent after re-rendering sibling component

我有一个包含两个子组件(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 在其创建和安装时使用 props 进行初始化,但随后您没有使用 props 的新值来更新它。

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

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

问题出在您的 PeopleList 组件中。呈现列表的状态对象是在组件安装时在构造函数中创建的,但是当它收到新值时您无法更新它。它总是会给你初始值。

可以引入一个生命周期方法,componentDidUpdate,这将允许您在新的 props 到达时将它们进行比较,并相应地更新状态.我建议您不要这样做,原因有二:

  1. 直接在组件状态中存储道具不是一个好习惯。您只是在上面的组件中创建状态的副本,这会在其中一个更新时产生混淆和陈旧值的机会。理想情况下,每条数据应该只存在于一个地方。

  2. 如果 PeopleList 所做的只是呈现您的数据,那么它根本不需要任何状态。它可以充当显示组件,将您的道具映射到位,而不必担心更新自身或管理自己的数据。这实际上会使它成为转换为功能组件的良好候选者。

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