javascript - 如何从 redux 中的动作事件重定向
问题描述
我想在触发操作后重定向客户端。我听说过react-redux-router
,但不确定如何在操作函数中正确实现它。
我关注了一点
https://stackoverflow.com/a/42985875/10865515
但是,当我提交经过验证的表单时,它不会重定向或刷新。
Actions.js
import { auth as firebaseAuth } from '../firebaseConfig'
import { push, browserHistory } from 'react-router-redux';
export const signUp = (user) => { return (dispatch) => {
firebaseAuth.createUserWithEmailAndPassword(user.email, user.password)
.then(() => {
dispatch({ type: 'SIGNUP_SUCCESS',
payload: (action, state, res) => {
return res.json().then(json => {
browserHistory.push('/');
return json;
});
},
});
}).catch((err) => {
dispatch({ type: 'SIGNUP_ERROR', err});
});
}
}
减速器.js
const initialState = {
emailSignUp: '',
passwordSignUp: '',
authError: null
}
export default (state = initialState, action) => {
switch (action.type) {
case 'SIGNUP_SUCCESS':
return ({
...state,
authError: null
})
case 'SIGNUP_ERROR':
console.log('signup error')
return ({
...state,
authError: action.err.message
})
default:
return state
}
}
注册.js
// ...
handleSubmit(event) {
event.preventDefault();
const {formData, errors} = this.state;
const {email, password} = formData;
const myError = this.props.authError;
const creds = {
email,
password
}
const register = this.props.signUp(creds);
if (register) {
console.log(creds);
}
}
解决方案
您应该实现react-router-dom
允许您访问history
对象以进行导航的库。
在触发动作创建者的组件中:
import { withRouter } from "react-router-dom"
然后在代码的底部,您调用连接:
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(myComponent))
现在您可以设置您的动作创建者以将历史记录作为参数。
您的操作文件:
const signUp = (creds, history) => {
//do some logic then go home
history.push("/")
}
因此,在您调用动作创建者的事件处理程序中,传入历史记录:
handleSubmit(event) {
event.preventDefault();
this.props.signUp(creds, this.props.history);
if (register) {
console.log(creds);
}
}
推荐阅读
- drop-down-menu - Coldfusion,下拉菜单,单个选项值可以包含多个变量吗?
- javascript - (PHP)如何使用会话保护目录(及其文件)
- reactjs - 关闭子组件后如何防止父组件状态重置为原始状态
- listview - NativeScript RadListView 图像动画不起作用
- python - 通过 Gitlab 合并请求向 Jenkins 传递参数
- python - 如何从 Colab 将文件输出到谷歌团队(共享)驱动器?
- html - Body 标签在我的代码中使用了两次。如何修复此错误以便我的代码可以通过验证?
- python - 训练 keras 模型时,维度如何工作?
- django - Django 测试返回一个 AnonymousUser 实例而不是新用户
- jquery - 在循环之外获取当前变体 id 并将其用于服务器端功能。WooCommerce / jQuery