【问题标题】:Why is my render() function getting called before my componentWillReceiveProps()?为什么我的 render() 函数在我的 componentWillReceiveProps() 之前被调用?
【发布时间】:2016-10-21 01:21:10
【问题描述】:

我正在查看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 仍然被调用。

我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-native jsx


    【解决方案1】:

    如果有东西作为道具进来,你可以通过this.props.something在你的组件中访问它

    componentWillReceiveProps 在组件接收新道具时被调用。初始渲染不调用此方法。

    【讨论】:

      【解决方案2】:

      请咨询https://facebook.github.io/react/docs/reusable-components.html

      // 您可以将上述任何一项与isRequired 链接起来以确保发出警告

      // 如果没有提供该道具,则显示。

      因此,PropTypes 不会停止它的 render() 函数,尽管程序员没有提供 required props 它只会在您的控制台上显示警告

      如果您想检查该道具,请将其添加到您的渲染中

      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>
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        • 2021-01-07
        • 2020-10-12
        • 1970-01-01
        相关资源
        最近更新 更多