簡體   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