【问题标题】:componentDidMount and constructorcomponentDidMount 和构造函数
【发布时间】:2018-08-23 18:41:11
【问题描述】:
 class ProductsIndex extends Component {

   constructor (props){
     super(props);

     console.log(this) // #1. this logs ProductsIndex component

     fetch('someUrl')
        .then(res => res.json())
        .then(res => console.log(this)) // #2. this logs ProductsIndex component

     fetch('someUrl')
        .then(res => res.json())
        .then(console.log)  // #3. this logs [{..},{..},{..},{..}]
   }


   componentDidMount(){
     fetch('someUrl')
        .then(res => res.json())
        .then(console.log)  // #4. this logs [{..},{..},{..},{..}]

   }

如上面的代码所示,#1 和#2 都指向同一个this。同样如图所示,#3 和 #4 都返回 same 数组。但是,为什么下面的代码不起作用??

 class ProductsIndex extends Component {

   constructor (props){
     super(props);

     fetch('someUrl')
       .then(res => res.json())
       .then(arr => {
          this.state = {
              array: arr
          }
       })
    }

它抛出一个错误,说 this.statenull,我真的不明白为什么。

下面的代码是解决方案。谁能解释一下到底有什么区别?

 class ProductsIndex extends Component {

   constructor (props){
     super(props);

     this.state = {
       array: []
     }
   }

   componentDidMount(){
      fetch('someUrl')
         .then(res => res.json())
         .then(arr => {
            this.setState({
                array: arr
             })
          })
    }

【问题讨论】:

  • 代码哪一行报错 **this.state is null ** ,不建议在构造函数中使用request的方式来设计。但是我实现了相同的代码codesandbox.io/s/z2641rm9l3,它没有给出任何错误。请告诉我们
  • 我试图 render() { return this.state.array.map( element =>

    { element.title }

    ) } 但它根本无法识别 现在我知道为什么了。我很困惑,毕竟这不是一个非常合理的问题。对不起:)

标签: reactjs asynchronous callback components es6-promise


【解决方案1】:

问题在于,当您在 constructor 中发出异步请求时,promise 可能会在 render 阶段执行后解决,此时 this.state 为空,而且因为您只是分配了

this.state = {
    array: arr
}

这不会导致重新渲染,因此组件不会反映更改。话虽如此,您应该将异步请求放在您在第二次尝试中提到的 componentDidMount 中,并且由于您在那里调用 setState,因此触发了 re-render 并且状态反映在 render

【讨论】:

  • 在构造函数中使用setState怎么样?
  • 不要:避免引入任何副作用或订阅。不要在构造函数中使用 setState() 设置状态。
  • @JayDesai 关心解释为什么?还是仅仅因为在构造函数中造成“副作用”通常是不好的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2017-01-21
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
相关资源
最近更新 更多