簡體   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