目标
使微调器运行直到加载数据。
我做什么
我关注了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;
}
}
}
控制台仅显示代码正在等待提取执行,而不会。
答案 0 :(得分:0)
似乎您将其向后退...您正在将状态初始化为true,然后在cdm中将其设置为false ...然后您正在检查加载是否为true(如果这样渲染Loader)...当然,它是不正确,您将其设置为false ...
更改为此:
constructor (props) {
super(props);
this.state = {
panelView: true,
loading: false <- here
}
}
async componentDidMount () {
this.setState({loading: true}); <- here
try {
await this.props.fetchEvents();
this.setState({loading: false}); <- and here...
console.log("BOOM")
} catch {
}
}
render() {
const {loading} = this.state;
const {panelView} = this.state;
if (loading) {
return <Loader />
}
return (
(Actual page)
)
}
答案 1 :(得分:0)
我发现了问题。问题是我从动作创建者那里返回了数据,而不是基于承诺的动作。
所以,而不是
const response = await axios.get('http://localhost:3090/events');
dispatch(setEvent(response.data));
return response.data;
应该已经
return axios.get('http://localhost:3090/events')
.then((response) => {
dispatch(setEvent(response.data));
});
答案 2 :(得分:0)
尝试这种方法
state = {
products: [],
loading: true,
}
async componentDidMount() {
// try catch just to make sure we had no errors
try {
const res = await fetch('http://api');
// wait for json to be ready
const data = await res.json();
this.setState({
loading: false,
data,
});
// console.log(product.data.attributes)
} catch (e) {
console.log(e);
}
}
render() {
const { data, loading } = this.state;
return (
<Container>
<Contents>
{loading ? 'loading..' : <Products data={data} />}
</Contents>
</Container>
);
}