【问题标题】:this.states initialized by separate function from out of constructor in Reactjsthis.states 由 Reactjs 中的构造函数之外的单独函数初始化
【发布时间】:2017-03-10 08:13:15
【问题描述】:

有时所有 this.states 都由单独的函数初始化 Reactjs 中的构造函数。我可以知道为什么吗?

例如:

class Articles extends React.Component {
    constructor(props) {
        super(props);
        this.initializer();
    }
    initializer(){
        this.state = {
            selectedArticle: this.props.article[0],
            showArticleDetails: true,
            showArticleContent: false
        };
    }
}

之后,this.initializer(); 在我们需要的地方使用。

【问题讨论】:

  • 您还应该将 props 作为参数传递并使用它而不是 this.props btw。
  • 谢谢你,但我不能准确地得到你。你能在这里简单地写一些代码吗?
  • 他的意思是你应该将 props 作为初始化器的参数传入:constructor(props) { super(props); this.initializer(props); } initializer(props){ this.state = { selectedArticle: props.article[0], showArticleDetails: true, showArticleContent: false }; }
  • 谢谢你们..你们俩的解释都很好..

标签: reactjs react-router react-jsx reactjs-flux


【解决方案1】:

这只是开发人员的偏好问题。状态可以在 constructor() 中初始化,但在这种情况下,为了清楚起见,开发人员选择将初始化代码放在单独的函数中。效果是一样的。

顺便说一句,您声明“this.initializer() 可在我们需要的任何地方使用。”从构造函数调用 initializer() 后,不应再次调用它。相反,您应该使用

this.setState({ newKey: newValue, ...})

【讨论】:

  • ok ok..那么如何在另一个组件中调用/使用'this.initializer()'
猜你喜欢
  • 1970-01-01
  • 2012-06-30
  • 2018-08-02
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多