我可以在 React.js 中更新组件的 props 吗? [英] Can I update a component's props in React.js?

查看:46
本文介绍了我可以在 React.js 中更新组件的 props 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始使用 React.js 后,似乎 props 是静态的(从父组件传入),而 state 根据事件变化.但是,我在文档中注意到对 componentWillReceiveProps,具体包括这个例子:

componentWillReceiveProps: function(nextProps) {this.setState({likesIncreasing: nextProps.likeCount >this.props.likeCount});}

这似乎意味着基于 nextPropsthis.props 的比较,组件的属性可以改变.我错过了什么?props 是如何变化的,或者我是否误解了它的调用位置?

解决方案

组件不能更新自己的 props,除非它们是数组或对象(即使可能,让组件更新自己的 props 是一种反模式),但可以更新它的 state 和它的孩子的 props.

例如,仪表板在其状态中有一个 speed 字段,并将其传递给显示此速度的 Gauge 子项.它的 render 方法只是 return .当仪表板调用 this.setState({speed: this.state.speed + 1}) 时,仪表会使用 speed 的新值重新呈现.>

就在这发生之前,Gauge 的 componentWillReceiveProps 被调用,以便 Gauge 有机会将新值与旧值进行比较.

After starting to work with React.js, it seems like props are intended to be static (passed in from the parent component), while state changes based upon events. However, I noticed in the docs a reference to componentWillReceiveProps, which specifically includes this example:

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

This seems to imply that the properties CAN change on a component based upon the comparison of nextProps to this.props. What am I missing? How do props change, or am I mistaken about where this gets called?

解决方案

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

For instance, a Dashboard has a speed field in its state, and passes it to a Gauge child thats displays this speed. Its render method is just return <Gauge speed={this.state.speed} />. When the Dashboard calls this.setState({speed: this.state.speed + 1}), the Gauge is re-rendered with the new value for speed.

Just before this happens, Gauge's componentWillReceiveProps is called, so that the Gauge has a chance to compare the new value to the old one.

这篇关于我可以在 React.js 中更新组件的 props 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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