Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - 我可以在React.js中更新组件的道具吗?(Can I update a component's props in React.js?)

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.

(在开始使用React.js之后,看起来props似乎是静态的(从父组件传入),而state基于事件而改变。)

However, I noticed in the docs a reference to componentWillReceiveProps , which specifically includes this example:

(但是,我在文档中注意到了componentWillReceiveProps的引用,它特别包含了这个例子:)

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 .

(这似乎意味着基于nextPropsthis.props的比较,属性可以在组件上发生变化。)

What am I missing?

(我错过了什么?)

How do props change, or am I mistaken about where this gets called?

(道具是如何改变的,还是我误解了它被称为何处?)

  ask by Matt Huggins translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(例如,仪表板在其状态下具有speed字段,并将其传递给显示此速度的Gauge子项。)

Its render method is just return <Gauge speed={this.state.speed} /> .

(它的render方法只是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 .

(当仪表板调用this.setState({speed: this.state.speed + 1}) ,将使用新的speed值重新渲染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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...