在显示任何UI之前,我需要调用一些服务来检索数据。返回的一些数据将用于在应用程序加载时有条件地呈现错误情况等。最好在ReactDOM.render()之前这样做吗?
答案 0 :(得分:0)
您应使用componentDidMount
致电给他们
您可以显示一个加载器,直到内容加载完成。
答案 1 :(得分:0)
您可以执行以下操作...
class Custom extends Component {
constructor(props) {
super(props);
this.state = { data: null, loading: false };
}
getData = () => {
// This is just to simulate a delayed API fetch/response.
this.setState({ loading: true }, () => {
setTimeout(() => this.setState({loading: false, data: {a: 'data loaded'}), 1000);
});
}
componentDidMount() {
this.getData(); // Call your data fetching method here...
}
render() {
const { loading, data } = this.state;
// you can also return a loading spinner instead of null;
// returning null ensures nothing is rendered in the DOM.
if (loading) return null;
// At this point, data is already available...
return (
<div>
// rest of your markup.
</div>
);
}
}
ReactDOM.render(<Custom />, document.getElementById('root'));