首页 文章

使用props在不使用React.createClass的情况下在反应中播种初始状态

提问于
浏览
3

我想使用来自我的道具的数据来播种我的组件状态,如下例所示:https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

getInitialState: function() {
    return {count: this.props.initialCount};
},

看看底部附近它说“但是,如果你明确说道,支柱只是组件内部控制状态的种子数据,那么它不是反模式:”这正是我想要做的 .

这在使用React.createClass时效果很好,但是我得到了一个错误 . 这意味着在道具可用后我没有机会计算它 . 请参阅https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property-initializers Headers 为"ES7+ Property Initializers"的部分

在该部分中,它们提供了一个示例,其中初始状态的计算类似于旧的getInitialState方法,只需在构造函数中设置this.state即可 . 但是,当我尝试这个时,this.props还没有设置 .

我已经搜索了第一次设置道具的生命周期方法,以便我可以设置当时的状态,但是我找不到任何这样的生命周期方法 .

我必须使用React.createClass,还是有一种方法可以在使用扩展React.Component的ES6类时播种我的initialState?

3 回答

  • 1

    这是一个示例类,您可以在其中使用它

    class Sample extends React.Component {
      constructor(props, context) {
        super(props, context);
    
        // replacement for componentWillMount
        this.state = {
          stateKey: props.stateVal
        };
      }
    
      render() {
        return (
          <div>{this.state.stateKey}</div>
        );
      }
    }
    
  • 1

    事实证明我在构造函数中没有将参数传递给super,这就是为什么道具在构造函数中不可用 . 我只需要改变这个:

    constructor() {
      super()
      ...
    }
    

    进入这个:

    constructor(...args) {
      super(...args)
      ...
    }
    

    我的问题与How to assign a prop value to a state in react非常相似,这让我误解了,所以这可能被认为是重复的 .

  • 0
    class Sample extends React.Component {
        constructor(props, context) {
            super(props, context);
             this.state = {
                   stateKey: ''
              };
           }
    
           componentWillReceiveProps(){
            this.setState({
               stateKey:this.props.data
             })
    
           render() {
              return (
               <div>{this.state.stateKey}</div>
           );
        }
    

    }

相关问题