Reactjs 正在设置组件状态,但render()方法中未定义this.props.state
我正在组件的componentDidMount()方法中发出get请求。我能够成功地发出请求并设置组件的状态。然而,当我试图在render()方法中访问state时,它返回为未定义。我猜这与javascript的异步性质有关,但似乎不知道如何正确设置状态,请等待以确保已设置状态,然后将其传递给我的render()方法,以便我可以在那里访问它。谢谢 Game.js(组件文件)Reactjs 正在设置组件状态,但render()方法中未定义this.props.state,reactjs,Reactjs,我正在组件的componentDidMount()方法中发出get请求。我能够成功地发出请求并设置组件的状态。然而,当我试图在render()方法中访问state时,它返回为未定义。我猜这与javascript的异步性质有关,但似乎不知道如何正确设置状态,请等待以确保已设置状态,然后将其传递给我的render()方法,以便我可以在那里访问它。谢谢 Game.js(组件文件) import React,{Component}来自'React'; 从“反应路由器”导入{Link}; 从“axios”
import React,{Component}来自'React';
从“反应路由器”导入{Link};
从“axios”导入axios;
导出默认类游戏扩展组件{
建造师(道具){
超级(道具)
此.state={
数据:[]
};
}
getReviews(){
常数this=这个;
获取(“/api/reviews”)
.然后(功能(响应){
_这是我的国家({
数据:response.data
});
console.log(_this.state.data);//显示这是一个对象数组。
})
.catch(函数(响应){
控制台日志(响应);
});
}
componentDidMount(){
这个.getReviews();
}
render(){
const allReviews=this.props.data.map((review)=>{
返回(
{review.username}
);
})
console.log(this.props.data);//在这里是未定义的。
返回(
{allReviews}
);
}
}
你是说这个.state.data
不是这个.props.data
?是的!非常感谢,我不知道我是怎么错过的。谢谢。
import React, { Component } from 'react';
import { Link } from 'react-router';
import axios from 'axios';
export default class Game extends Component {
constructor(props) {
super(props)
this.state = {
data: []
};
}
getReviews() {
const _this = this;
axios.get('/api/reviews')
.then(function(response) {
_this.setState({
data: response.data
});
console.log(_this.state.data); // shows that this is an array of objects.
})
.catch(function(response) {
console.log(response);
});
}
componentDidMount() {
this.getReviews();
}
render() {
const allReviews = this.props.data.map((review) => {
return (
<li>{review.username}</li>
);
})
console.log(this.props.data); // comes in as undefined here.
return (
<div>
{allReviews}
</div>
);
}
}