gpt4 book ai didi

javascript - 异步获取 JSON 然后渲染组件

转载 作者:行者123 更新时间:2023-11-28 14:51:49 24 4
gpt4 key购买 nike

我有一个组件,它必须下载一个 JSON 文件,然后然后迭代它并在屏幕上显示 JSON 中的每个元素。

我对 React 还算陌生,以前是 ng dev。在 Angular 中,我曾经使用生命周期钩子(Hook)来做到这一点,例如ngOnInit/ngAfterViewInit(获取一些 JSON 文件,然后执行迭代函数)。我怎样才能在React中实现它?是否可以通过生命周期 Hook 来实现它,例如 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 中发出 AJAX 请求是可行的。 https://facebook.github.io/react/docs/react-component.html#componentwillmount

您也可以根据您的具体需求将该逻辑应用到构造函数中。 https://facebook.github.io/react/docs/react-component.html#constructor

export default class ExampleClass extends React.Component {
constructor(props) {
super(props)
this.state = {
data: [],
}
axios.get(/*someURL*/)
.then(function (response) {
this.setState({data: response.data});
})
.catch(function (error) {
console.log(error);
})
}
}

关于javascript - 异步获取 JSON 然后渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com