gpt4 book ai didi

reactjs - componentDidMount 和构造函数

转载 作者:行者123 更新时间:2023-12-03 13:22:02 26 4
gpt4 key购买 nike

 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 都返回相同数组。但是,为什么下面的代码不起作用?

 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
})
})
}

最佳答案

问题是,当您在构造函数中发出异步请求时,promise可能会在render阶段执行后得到解决,并且此时点 this.state 为 null 并且因为您刚刚分配

this.state = {
array: arr
}

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

关于reactjs - componentDidMount 和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com