Gil*_*tzi 1 reactjs react-router redux redux-thunk react-router-redux
在我的React/Redux应用程序中,我有一些异步操作.假设用户getData向服务器发起请求.立即GET_DATA_REQUEST被分派和getDataAJAX调用是在它的途中到服务器.
成功或失败后,将相应地分派一个GET_DATA_SUCCESS或多个GET_DATA_FAILURE动作,并将数据呈现给UI.
现在,我希望我的应用程序将历史状态(使用react-router-redux)作为对AJAX回调的反应.意思是,一旦成功,用户被"重定向"到另一个URL(路由),显示依赖于新接收的数据的不同模块.
我意识到在reducer中使用这个功能是一个非常糟糕的主意,因为它不再是纯粹的(URL更改是副作用).
有什么想法吗?
谢谢
我相信这是处理你的情况的好方法.
首先,您应该在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
}
Run Code Online (Sandbox Code Playgroud)
然后,在连接到reducer的组件中,您应该检查componentDidUpdate函数中"redirect"的值.
componentDidUpdate(){
let {redirect} = this.props.yourReducerState;
if(redirect === true){
this.context.router.push("new-url");
}
}
Run Code Online (Sandbox Code Playgroud)
最后,您应该重置componentWillUnmount上的"重定向"
希望能帮助到你!
小智 6
另一个很好的方法.我从这个Udemy课程中学到了这一点,我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>
Run Code Online (Sandbox Code Playgroud)
在动作创建者中,放置它
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 };
Run Code Online (Sandbox Code Playgroud)
这里的GitHub演示可以找到相关的代码和整个项目.斯蒂芬·格里德是一位优秀的老师!
这是一种不将重定向放入状态树的方法.
| 归档时间: |
|
| 查看次数: |
4695 次 |
| 最近记录: |