【发布时间】:2017-09-23 22:16:29
【问题描述】:
我有一个函数 fetchTweets,它使用给定的参数 a 和 b 获取推文。
函数 toPageTwo 调用 fetchTweets 函数,然后将用户重定向到正在显示获取的数据的另一个页面
toPageTwo() {
this.fetchTweets(param1,param2);
this.props.router.push(`/page2`);
}
}
当用户点击发送按钮时正在执行toPageTwo():
<Button onClick={::this.toPageTwo}>
Send
</Button>
如何确保只有在正确获取推文后才加载 page2?
更新:
我正在使用 Redux 和 Axios 来获取推文,并且启动获取等的按钮位于侧边栏中。我的文件树如下所示:
src
redux
actions
tweets.js
common
sidebar.js
tweets.js:
import axios from "axios";
export function fetchTweets(a,b){
return function(dispatch) {
axios.get("http://127.0.0.1:5000/?a="+a+"&b="+b)
.then((response) => {
dispatch({type: "FETCH_TWEETS_FULFILLED", payload: response.data})
})
.catch((err) => {
dispatch({type: "FETCH_TWEETS_REJECTED", payload: err})
})
}
}
如果我将“.then”添加到 FETCH_TWEETS_FULFILLED 调度,我可以在获取后控制台日志。但是这不适用于 this.props.router.push(/page2)
sidebar.js:
-- IMPORTS --
@connect((state) => state)
@withRouter
class ApplicationSidebar extends React.Component {
-- BUNCH OF FUNCTIONS --
fetchTweets(a,b) {
this.props.dispatch(fetchTweets(a,b));
}
toPageTwo() {
fetchTweets(param_a,param_b);
this.props.router.push(`/page2`);
}
}
render() {
return (
-- SIDEBAR STUFF --
<Button onClick={::this.toPageTwo}>
Send
</Button>
);
}
由于某种原因,创建回调函数会产生与常规函数相同的结果:后一个函数在第一部分(推文获取)完成之前执行。
谢谢!
【问题讨论】:
-
你究竟是如何获取推文的?
-
我在原始帖子中添加了更多内容。谢谢!
-
建议:用 redux 标签标记你的问题。
标签: reactjs callback promise redux