【发布时间】:2019-04-14 04:32:21
【问题描述】:
目标
让微调器运行直到数据加载。
我做了什么
我关注了this article
我也尝试了常规的承诺和then,但没有成功。
会发生什么
console.log 立即显示“boom”,因此无需等待数据获取。没有错误。
EventPage.js
constructor (props) {
super(props);
this.state = {
panelView: true,
loading: true
}
}
async componentDidMount () {
try {
await this.props.fetchEvents();
this.setState({loading: false});
console.log("BOOM")
} catch {
}
}
render() {
const {loading} = this.state;
const {panelView} = this.state;
if (loading) {
return <Loader />
}
return (
(Actual page)
)
}
eventActionCreator fetchEvents
export const fetchEvents = () => {
return async dispatch => {
try {
const response = await axios.get('http://localhost:3090/events');
dispatch(setEvent(response.data));
return response.data;
} catch (e) {
return e;
}
}
}
控制台只是显示代码正在等待 fetch 执行,它没有。
【问题讨论】:
-
请添加一个带有来自 Stackoverflow 的 JS sn-p 功能的实时示例。
-
当您说“没有成功”时——实际发生了什么?控制台中是否有错误? “BOOM”会写吗?
-
@bluejack 我添加了详细信息
-
您的代码中似乎没有错误..您可以添加更多详细信息或工作演示吗?
-
@ma_dev_15 是的...看看下面的答案以及代码沙箱上的现场演示...他在他的 setState 中将 loading 设置为 false ...然后有条件渲染 Loading如果是真的……
标签: reactjs redux async-await es6-promise