【问题标题】:Redux - Change URL when an async action is dispatchedRedux - 调度异步操作时更改 URL
【发布时间】:2016-08-21 13:19:48
【问题描述】:
在我的 React/Redux 应用程序中,我有一些异步操作。
假设用户向服务器发起getData 请求。立即发送GET_DATA_REQUEST,并且getData AJAX 调用正在发送到服务器。
无论成功还是失败,都会相应地调度 GET_DATA_SUCCESS 或 GET_DATA_FAILURE 操作并将数据呈现到 UI。
现在,我希望我的应用程序推送历史状态(使用 react-router-redux)作为对 AJAX 回调的反应。这意味着,成功后,用户将被“重定向”到另一个 URL(路由),显示依赖于新接收数据的不同模块。
我意识到在 reducer 中具有此功能是一个非常糟糕的想法,因为它不再是纯粹的(URL 更改是一个副作用)。
有什么想法吗?
谢谢
【问题讨论】:
标签:
reactjs
react-router
redux
redux-thunk
react-router-redux
【解决方案1】:
我相信这是处理您的情况的好方法。
首先,你应该在你的reducer中添加一个新的属性来判断你是否想要重定向。
类似的东西
const initialState = {
...
redirect : false // You could use a String with the new url instead of true/false
....
}
switch ...
case GET_DATA_SUCCESS:
return {
...state,
redirect:true,
}
case GET_DATA_FAILURE;
return {
...state,
redirect:false
}
然后,在连接到你的reducer的组件中,你应该检查componentDidUpdate函数中“redirect”的值。
componentDidUpdate(){
let {redirect} = this.props.yourReducerState;
if(redirect === true){
this.context.router.push("new-url");
}
}
最后,您应该在 componentWillUnmount 上重置“重定向”
希望对你有帮助!
【解决方案2】:
实现此目的的另一种好方法。我是从this Udemy course 那里学到的,我 100% 推荐它。
在组件(你要提交的表单)内部,放置这个表单提交事件处理程序,它会调用动作。
submit(values) {
this.props.xxxActionCreator(() => {
this.props.history.push("/");//history is provided by react-route, .push("/") will direct app back to root path.
});
}
render() {
<form onSubmit={this.submit.bind(this)} >
.... </form>
在动作创建器里面,放这个
export default function xxxAction(callback) {
const request = axios.get('...url').then(() => callback()); //here the function (callback) that was passed into this.props.xxxActionCreator() will be invoked.
//.then() is provided by promise. This line of code means the callback (which redirects you to the root path) will be invoked, once the promise (async) is resolved.
return { type: SOME_ACTION, payload: XXX };
GitHub demo在这里你可以找到相关代码和整个项目。由伟大的老师 Stephen Grider 亲切介绍!
这是一种不将重定向放入状态树的方法。