[英]Why is my render() function getting called before my componentWillReceiveProps()?
我在这里查看文档https://facebook.github.io/react/docs/component-specs.html ,无法弄清楚为什么我遇到这个问题。
我的情况是我有一个像
export default class MyComponent extends Component
{
constructor(props)
{
super(props);
this.state = { something: null };
}
render()
{
// ... uses something
}
ProductSorter.propTypes =
{
something: PropTypes.string.isRequired
}
而且我的render
函数当然假设something
非null
因为该属性是必需的。 但是,似乎在收到用于something
道具的道具之前仍然需要调用render
。
此外,我正在使用MyComponent
{ valueIsNonNull && <MyComponent something={value} }
并且仍然在something
传递之前调用render
。
我究竟做错了什么?
如果有东西作为道具进入,则可以通过this.props.something
在组件内部访问它
当组件正在接收新的道具时,调用componentWillReceiveProps。 初始渲染不调用此方法。
请查阅https://facebook.github.io/react/docs/reusable-components.html
//您可以使用
isRequired
上述任何内容,以确保发出警告如果未提供道具,则显示//。
因此,尽管程序员没有提供required props
,但PropTypes不会停止其render()
函数,它只会在您的控制台上显示警告
如果要检查该道具,请将其添加到渲染中
render () {
if(typeof this.props.SomeRequiredProp === 'undefined') return null
{/*the following will renders when the required prop is supplied*/}
<div>Rendered! {this.props.SomeRequiredProp}</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.