【发布时间】:2017-10-28 13:35:35
【问题描述】:
我有一个组件,它必须下载一个 JSON 文件并然后对其进行迭代并在屏幕上显示 JSON 中的每个元素。
我对 React 有点陌生,以前是 ng dev。在 Angular 中,我曾经使用生命周期钩子来做这件事,例如ngOnInit/ngAfterViewInit(获取一些 JSON 文件,然后午餐迭代函数)。我如何在 React 中实现它?是否可以通过生命周期钩子来访问它,例如 ComponentWillMount 或 ComponentDidMount。
我的代码(肯定是错的):
export default class ExampleClass extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentWillMount(){
getData();
}
render() {
return (
<ul>
{this.state.data.map((v, i) => <li key={i}>{v}</li>)}
</ul>
)
};
}
const getData = () => {
axios.get(//someURL//)
.then(function (response) {
this.setState({data: response.data});
})
.catch(function (error) {
console.log(error);
})
};
如何在渲染组件之前强制 React 获取 JSON?
非常感谢。
【问题讨论】:
-
是的,使用
ComponentWillMount是一种方法,只要确保您正确绑定this以便this.setState引用组件!您也可以只在构造函数中发出 get 请求。
标签: javascript json reactjs promise