Reactjs 组件安装和构造函数
如上面的代码所示,#1和#2都指向相同的。同样如图所示,#3和#4都返回相同的数组。但是,为什么下面的代码不起作用Reactjs 组件安装和构造函数,reactjs,asynchronous,callback,components,es6-promise,Reactjs,Asynchronous,Callback,Components,Es6 Promise,如上面的代码所示,#1和#2都指向相同的。同样如图所示,#3和#4都返回相同的数组。但是,为什么下面的代码不起作用 class ProductsIndex extends Component { constructor (props){ super(props); console.log(this) // #1. this logs ProductsIndex component fetch('someUrl') .then(res =
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 [{..},{..},{..},{..}]
}
它抛出了一个错误,说this.state是null,我真的不明白为什么
下面的代码是解决方案。有人能解释一下到底有什么区别吗
class ProductsIndex extends Component {
constructor (props){
super(props);
fetch('someUrl')
.then(res => res.json())
.then(arr => {
this.state = {
array: arr
}
})
}
问题是,当您在
构造函数
中放置异步请求时,承诺
可能会在执行呈现
阶段后得到解决,此时此.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
})
})
}
这不会导致重新渲染,因此组件不会反映更改。已经说过,您应该将异步请求放在您在第二次尝试中提到的
componentDidMount
中,并且由于您在那里调用了setState
,会触发re render
,并且render中反映的状态代码中的哪一行给出了错误**this.state为null**,在构造函数内部使用请求的方法不适合设计。但是我实现了相同的代码,没有给出任何错误。请告诉我们我试图render(){返回此.state.array.map(element=>{element.title})},但它根本无法识别这一点,现在我知道了原因。。我很困惑,这毕竟不是一个很合理的问题。抱歉:)在构造函数中使用setState
如何?不要:避免引入任何副作用或订阅。不要在构造函数中使用setState()来设置状态。@JayDesai想解释一下原因吗?或者仅仅因为在构造函数中造成“副作用”通常是不好的?
this.state = {
array: arr
}