反应:为什么在更改道具时子元素不会更新 [英] React: why child component doesn't update when prop changes

查看:93
本文介绍了反应:为什么在更改道具时子元素不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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


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

解决方案

如果父母的道具发生了变化,但是如果它的状态发生变化,则不要重申:)

你所显示的是这样的:
https://facebook.github.io/react/tips/communicate-between-components.html


它会通过道具将数据从父项传递给子项,但是没有重新逻辑。



您需要为父级设置一些状态,然后在父级更改状态下重新显示子级。
这可能有所帮助。
https://facebook.github.io/react/ tips / expose-component-functions.html


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>
  }
}

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

解决方案

Because children do not rerender if the props of the parent change, but if its STATE changes :)

What you are showing is this: https://facebook.github.io/react/tips/communicate-between-components.html

It will pass data from parent to child through props but there is no rerender logic there.

You need to set some state to the parent then rerender the child on parent change state. This could help. https://facebook.github.io/react/tips/expose-component-functions.html

这篇关于反应:为什么在更改道具时子元素不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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