【问题标题】:Using props to seed initial state in react without using React.createClass在不使用 React.createClass 的情况下使用 props 在 react 中播种初始状态
【发布时间】:2016-07-14 14:04:55
【问题描述】:

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

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

看看底部附近写着“但是,如果你明确表示 prop 只是组件内部控制状态的种子数据,这不是反模式:”这正是我想要做的。

这在使用 React.createClass 时效果很好,但如果可能的话,我想使用 ES6 类来做到这一点。但是在使用 ES6 类时,初始状态是作为类的静态属性提供的。如果你尝试实现 getInitialState(),你会得到一个错误。这意味着在道具可用后我没有机会计算它。请参阅https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property-initializers 上标题为“ES7+ 属性初始化器”的部分

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

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

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

【问题讨论】:

    标签: reactjs


    【解决方案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>
        );
      }
    }
    

    【讨论】:

    • this.props 在构造函数中未定义。您想直接从props arg 获取值:stateKey: props.stateVal
    【解决方案2】:

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

    constructor() {
      super()
      ...
    }
    

    进入这个:

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

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

    【讨论】:

      【解决方案3】:
        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>
             );
          }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-05
        • 2022-01-24
        • 2023-03-08
        • 2023-01-13
        • 1970-01-01
        • 2022-01-25
        • 2019-03-15
        • 2015-11-30
        相关资源
        最近更新 更多