在开始使用React.js后,似乎道具是静态的(从父组件传入),而状态是基于事件变化的。然而,我注意到在文档中有一个componentWillReceiveProps的引用,其中特别包括这个例子:
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
这似乎意味着,基于nextProps与This .props的比较,组件的属性可以改变。我错过了什么?道具是如何变化的,或者我弄错了这个在哪里被调用?
如果使用重组,则使用mapProps从传入的道具派生出新的道具
例子:
import { compose, mapProps } from 'recompose';
const SomeComponent = ({ url, onComplete }) => (
{url ? (
<View />
) : null}
)
export default compose(
mapProps(({ url, storeUrl, history, ...props }) => ({
...props,
onClose: () => {
history.goBack();
},
url: url || storeUrl,
})),
)(SomeComponent);