【问题标题】:ReactJS - Children do not re-render correctly after change in parentReactJS - 更改父级后,子级无法正确重新渲染
【发布时间】:2017-02-08 21:32:09
【问题描述】:

我是 ReactJS 的新手,所以我尝试开发一个小应用程序来了解它是如何工作的。它是一个从 API 中获取数据(用户)并显示出来的接口。我还可以添加数据和删除用户。添加工作正常,但我在删除时遇到问题。

Json 组件(父级)

class Json extends React.Component {
  constructor(props){
    super(props);
    this.state = {items: []}
    this.updateDelete = this.updateDelete.bind(this)
    this.updateAdd = this.updateAdd.bind(this)
  }

  componentDidMount() {
    this.grabusers();
  }

  grabusers() {
    var request = new Request('http://localhost:4000/users', {
         method: 'GET',
         mode: 'cors'
    });
    fetch(request).then(result=>result.json()).then(items=>this.setState({items: items}))
  }

  updateDelete(user){
    var i = this.state.items.indexOf(user)
    var items = this.state.items
    items.splice(i,1)
    this.setState({items: items})
  }

  updateAdd(user){
    var items = this.state.items
    items.push(user)
    this.setState(items)
  }

  render(){
    return (
      <div>
        <Form updateJson={this.updateAdd}/>
        <div className="row">
          {this.state.items.map(item => <Card item={item} updateJson={this.updateDelete}/>)}
        </div>
      </div>
    )
  }
}

卡片组件(子)

class Card extends React.Component {
  constructor(props){
    super(props)
    this.state = {item: props.item}
    this.delete = this.delete.bind(this)
  }

  delete(){
    var request = new Request('http://localhost:4000/users/'+this.state.item._id, {
         method: 'DELETE',
         mode: 'cors'
    });
    fetch(request).then(() => this.props.updateJson(this.state.item))
  }

  render(){
    return (
      <div className="col-md-4">
      <div className="Card row">
        <div className="col-md-2"><span className="glyphicon glyphicon-user icon" aria-hidden="true"></span></div>
        <div className="col-md-10"><Fullname firstname={this.state.item.firstname} lastname={this.state.item.lastname}/>
        <City city={this.state.item.city}/></div>
        <button type="button" className="btn btn-danger buttondelete" onClick={this.delete}>Delete</button>
      </div>
      </div>)
  }
}

当我删除用户时,Json 的 state.items 会根据删除进行相应更新,但卡片不会相应地重新渲染。事实上,道具被传递给卡片,但它始终是从视图中删除的最后一个,而 console.log 显示一切都很好......

【问题讨论】:

  • 在使用地图渲染时尝试传递密钥
  • 最佳实践是将delete方法作为props从父组件传递给子组件,然后将子组件转换为纯功能组件。通过这种方式可以更轻松地管理状态。

标签: javascript api reactjs parent children


【解决方案1】:

可能是在渲染没有key 属性的组件数组时出现的问题。

当你在 React 中渲染一个组件数组时,就像这里:

{this.state.items.map(item =&gt; &lt;Card item={item} updateJson={this.updateDelete}/&gt;)}

您需要为每个项目指定一个唯一的key 属性。它将帮助 React 知道哪个元素被更改并应该重新渲染。

例如:

{this.state.items.map((item, index) =&gt; &lt;Card key={'card-' + index} item={item} updateJson={this.updateDelete}/&gt;)}

阅读这篇文章lists-and-keys.html

【讨论】:

  • 谢谢!我用 shortid 创建了密钥 :) 我在 Json 中移动了前代和后代,它可以工作:D
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 2020-06-26
  • 2018-12-28
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2017-11-16
相关资源
最近更新 更多