重新渲染同级组件后,在父级中渲染子组件

时间:2020-07-20 22:13:20

标签: reactjs react-component

我有一个父组件,其中包含两个子组件(AddPersonForm和PeopleList)。当我通过AddPersonForm提交名称时,我希望它会在PeopleList组件中呈现,但不会。

这是我的 AddPersonForm

Failed to load resource: the server responded with a status of 403 ()
createError.js:16 Uncaught (in promise) Error: Request failed with status code 403
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.p.onreadystatechange (xhr.js:61)

我的 PeopleList 组件:

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>
     );
  }   

现在是父组件, ContactManager

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>;
   } 
} 

请问我做错了还是没有做?

2 个答案:

答案 0 :(得分:1)

在创建PeopleList并挂载道具时,您正在使用它们进行初始化,但是您没有使用props的新值进行更新。

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

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

答案 1 :(得分:1)

问题出在您的PeopleList组件中。挂载组件时,会在构造函数中创建呈现列表的状态对象,但是当它接收到新值时,您将无法对其进行更新。它将始终为您提供初始值。

可以引入一种生命周期方法componentDidUpdate,该方法可让您比较以前的道具与新道具到达时的状态,并相应地更新状态。我建议您不要这样做有两个原因:

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

  2. 如果所有PeopleList都在渲染数据,那么它根本不需要任何状态。它可以充当显示组件,将道具映射到适当的位置,而不必担心自己更新或管理自己的数据。实际上,这将使其成为转换为功能组件的理想选择。

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