簡體   English   中英

如何在 React 中渲染和更新來自父組件的子元素?

[英]How to render and update child elements coming from a parent component in React?

我有一個由父組件擁有並在子組件中呈現的字符串集合的問題。 我實現了這一點,我還可以從子組件執行父方法(刪除)。 但是當集合在父視圖中更新時,它不會在子視圖中更新。 任何想法?

這是父母:

export class App extends React.Component {

  constructor() {
    super();
    this.state = {
      countries: ['Country 1', 'Country 2', 'Country 3']
    };
  }

  deleteCountry = (name) => {
    this.setState(this.state.countries.filter(country => country !== name));
  }

  render() {
    return <Router>
      <NavBar></NavBar>
      <Switch>
        <Route path="/" exact component={Jobs}></Route>
        <Route path="/countries" exact render={(props) => <Countries {...props} collection={this.state.countries} delete={this.deleteCountry}/>}></Route>
      </Switch>
    </Router>
  }
}
export default App;

這是孩子:

export class Countries extends React.Component {
  render() {
    return <div>
      <h3>Countries</h3>
      <ul>
        {this.props.collection.map((country) => { 
          return <li key={country}>
            {country}
            <button onClick={() => this.props.delete(country)}>Eliminar</button>
          </li>
        })}
      </ul>
    </div>;
  }
}

非常感謝您的關注!

您的deleteCountry方法似乎沒有在 state 中設置正確的鍵:

deleteCountry = (name) => {
  this.setState({
    countries: this.state.countries.filter(country => country !== name)
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM