【问题标题】:is there a way to access new context api within constructor?有没有办法在构造函数中访问新的上下文 api?
【发布时间】:2019-09-08 11:03:31
【问题描述】:

有没有办法在构造函数中访问新的上下文 api?

我想在构造函数中获取上下文,但现在我只在 componentDidMount 之后获取。 演示:https://codesandbox.io/s/dank-wave-yy8uq

我尝试将第二个参数添加到构造函数中,我可以在构造函数中获取上下文。但是我不知道这是否正确?或者还有其他方法吗? 演示:https://codesandbox.io/s/quizzical-sinoussi-ln7lg

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    使用 context 作为第二个参数并将其传递给 super 是正确的方法。

    constructor(props, context) {
      super(props, context);
      // ...
    

    【讨论】:

      【解决方案2】:

      我完全同意jagster 的回答。我还要补充一点,如果您不使用constructor(props) 中的props 参数,然后将其传递给super(props),那么它在构造函数中也将是undefined

      【讨论】:

        猜你喜欢
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        相关资源
        最近更新 更多