React:为什么当 prop 更改时子组件不更新 [英] React: why child component doesn't update when prop changes

查看:240
本文介绍了React:为什么当 prop 更改时子组件不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在下面的伪代码示例中,当 Container 更改 foo.bar 时,Child 不会重新渲染?

Why in the following pseudo-code example Child doesn't re-render when Container changes foo.bar?

Container {
  handleEvent() {
    this.props.foo.bar = 123
  },

  render() {
    return <Child bar={this.props.foo.bar} />
}

Child {
  render() {
    return <div>{this.props.bar}</div>
  }
}

即使我在修改Container中的值后调用forceUpdate(),Child仍然显示旧值.

Even if I call forceUpdate() after modifying the value in Container, Child still shows the old value.

推荐答案

更新子级,使其属性 'key' 等于名称.每次键值更改时,组件都会重新渲染.

Update the child to have the attribute 'key' equal to the name. The component will re-render every time the key changes.

Child {
  render() {
    return <div key={this.props.bar}>{this.props.bar}</div>
  }
}

这篇关于React:为什么当 prop 更改时子组件不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆