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

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

问题描述

开始使用React.js后,似乎 props 是静态的(从父组件传入),而 state 根据事件进行更改。但是,我在文档中注意到 componentWillReceiveProps ,具体包括此示例:

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

这似乎意味着属性可以根据比较在组件上发生变化 nextProps this.props 。我错过了什么?道具如何改变,或者我错误地调用它的位置?

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.

例如,仪表板在其状态下具有 speed 字段,并将其传递给显示此速度的Gauge子项。它的渲染方法只是 return< Gauge speed = {this.state.speed} /> 。当仪表板调用 this.setState({speed:this.state.speed + 1})时,将使用速度。

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.

在此之前,调用Gauge的 componentWillReceiveProps ,以便Gauge有机会将新值与旧值进行比较。

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中更新组件的道具吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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