繁体   English   中英

为什么子组件没有在组件树中更新?

[英]Why child component doesn't get updated in components tree?

我尝试将 state 传递给孩子,以更新对象列表。 当我添加一个条目时,它不会在子组件中呈现。 我还检查了state.contacts实际上被替换为新数组,但它没有用。


  constructor(props) {
    this.super(props);
  }

  removeContact(event) {
    this.setState((state) => {
      state.contacts = state.contacts.filter((contact) => contact.key !== event.target.key )
      return state;
    })
  }

  render() {
    return (
      <Fragment>
        <span>{this.props.contact.name}</span>
        <span>{this.props.contact.phone}</span>
        <span>{this.props.contact.adress}</span>
        <a href="#" onClick={this.removeContact}>X</a>
      </Fragment>
    )
  }
}

class Contacts extends Component {

  constructor(props) {
    super(props);
    this.state = { contacts: props.contacts };
  }

  render() {
    console.log(this.state.contacts); // always displays empty array
    return (
      <div>
        {this.state.contacts.map((contact, index) => 
          <div>
            <Contact key={index} contact={contact} contacts={this.state.contacts}/>
          </div>
        )}
      </div>
    )
  }
}

class App extends Component {
  state = {
    time: new Date(),
    name: "",
    phone: "",
    adress: "",
    contacts: []
  }

  change = (event) => {
    let nameOfField = event.target.name;

    this.setState({[nameOfField]: event.target.value})
  }

  // click = () => { 
  //   this.setState((state) => {
  //     state.time = new Date();
  //     return state;
  //   })
  // }

  addContact = () => {
    let name = this.state.name;
    let phone = this.state.phone;
    let adress = this.state.adress;

    this.setState((state) => {
      return {contacts: [ ... state.contacts.concat([{name, adress, phone}])]}
    });

  }

  render() {
    return (
    <div className="App">
      <Timestamp time={this.state.time}/>
      <Contacts contacts={this.state.contacts}/>
      <input name="name" value={this.state.name} onChange={this.change} placeholder="Name"/>
      <input name="phone" value={this.state.phone} onChange={this.change} placeholder="Phone"/>
      <input name="adress" value={this.state.adress} onChange={this.change} placeholder="Adress"/>
      <button onClick={this.addContact}>Add contact</button>
    </div> 
    )
  }
}

ReactDOM.render(<App time={Date.now().toString()}/>, document.getElementById('root'));

如果将值传递给组件,则应将它们呈现为props 无需复制到子组件 state 中:

class Contacts extends Component {

  render() {
    console.log(this.props.contacts); // use props instead of state
    return (
      <div>
        {this.props.contacts.map((contact, index) => 
          <div>
            <Contact key={index} contact={contact} contacts={this.props.contacts}/>
          </div>
        )}
      </div>
    )
  }
}

使用this.props是一种很好的做法,因为它允许 React确定性地渲染(如果传递了相同的 props,则返回相同的渲染结果)。

您当前正在从其子组件Contacts中的Contact 您不能直接从子组件中更新父 state。

您可以做的是在您的Contacts组件中创建一个removeContact function 并将整个 function 传递给您的Contact组件。 这样,当您在子组件中调用removeContact时,它实际上会从父组件调用它,修改父组件 state,并使用新的 state 更新它的所有子组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM