【发布时间】: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.state 是 null,我真的不明白为什么。
下面的代码是解决方案。谁能解释一下到底有什么区别?
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