我是 React 的新手,一直在努力编写代码,但找不到我做错了什么,
这是我的代码
export class MainPage extends Component {
constructor(props){
super(props);
this.state = {
pn_list : []
}
}
componentWillMount() {
axios.get('http://localhost:8080/pn_info/over_30')
.then((response) => {
this.setState(
{pn_list : response.data}
)
})
}
render() {
return(
<div>
<SelectionMenu data={this.state.pn_list}/>
</div>
)
};
};
export default MainPage;
基本上我的代码试图在 SelectionMenu
完成之前呈现 componentWillMount
组件,但我不明白为什么会这样。
我尝试在 axios 获得响应后 console.log(this.state.pn_list)
但看起来 setState
方法没有更新它,因为它仍然记录空数组。
你能帮我吗?
答案 0 :(得分:1)
对于 AJAX 调用和填充状态,您应该使用 componentWillMount
而不是 componentDidMount
。
查看更多信息:https://reactjs.org/docs/faq-ajax.html#where-in-the-component-lifecycle-should-i-make-an-ajax-call