繁体   English   中英

为什么在我的componentWillReceiveProps()之前调用render()函数?

[英]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函数当然假设somethingnull因为该属性是必需的。 但是,似乎在收到用于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM