背景:
我正在创建一个 Login
组件。
saga.js
由 3 个函数组成
1. rootSaga
。它将执行sagas
里面的列表
2. watchSubmitBtn
。它会观察提交按钮的点击并发送一个 Action 。
3. shootApiTokenAuth
会接收派发的action
并处理axios.post
返回值为promise
对象
在行动:
后端返回 400
给 React
。这种情况没问题,我可以轻松读取 payload
并在 render()
中显示。但是当返回 200
时。
我需要让用户转到 url /companies
。
尝试:
我曾尝试将 this.props.history.push('/companies');
放在 componentWillUpdate()
中,但它不起作用。我必须点击 Submit
两次才能让 React 知道 token
已保存。
登录.js
import React, {Component} from 'react';
import ErrorMessage from "../ErrorMessage";
import {Field, reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import {validate} from '../validate';
import {SUBMIT_USERNAME_PASSWORD} from "../../constants";
class Login extends Component {
constructor(props) {
//Login is stateful component, but finally action will change
//reducer state
super(props);
const token = localStorage.getItem('token');
const isAuthenticated = !((token === undefined) | (token === null));
this.state = {
token,
isAuthenticated,
message: null,
statusCode: null
};
}
onSubmit(values) {
const {userid, password} = values;
const data = {
username: userid,
password
};
this.props.onSubmitClick(data);
}
componentWillUpdate(){
console.log('componentWillUpdate');
if(this.props.isAuthenticated){
this.props.history.push('/companies');
}
}
renderField(field) {
const {meta: {touched, error}} = field;
const className = `'form-group' ${touched && error ? 'has-danger' : ''}`;
console.log('renderField');
return (
<div className={className}>
<label>{field.label}</label>
<input
className="form-control"
type={field.type}
placeholder={field.placeholder}
{...field.input}
/>
<div className="text-help">
{touched ? error : ''}
</div>
</div>
);
}
render() {
const {handleSubmit} = this.props;
return (
<div>
<ErrorMessage
isAuthenticated={this.props.isAuthenticated}
message={this.props.message}
/>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
name="userid"
component={this.renderField}
placeholder="User ID"
type="text"
/>
<Field
name="password"
component={this.renderField}
placeholder="Password"
type="password"
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<a className='btn btn-primary' href="https://www.magicboxasia.com/">Sign up</a>
</div>
);
}
}
const onSubmitClick = ({username, password}) => {
return {
type: SUBMIT_USERNAME_PASSWORD,
payload: {username, password}
};
};
const mapStateToProps = (state, ownProps) => {
return {
...state.login
}
};
export default reduxForm({
validate,
form: 'LoginForm'
})(
connect(mapStateToProps, {onSubmitClick})(Login)
);
传奇.ja
const shootApiTokenAuth = (values) =>{
const {username, password} = values;
return axios.post(`${ROOT_URL}/api-token-auth/`,
{username, password});
};
function* shootAPI(action){
try{
const res = yield call(shootApiTokenAuth, action.payload);
yield put({
type: REQUEST_SUCCESS,
payload: res
});
}catch(err){
yield put({
type: REQUEST_FAILED,
payload: err
});
}
}
function * watchSubmitBtn(){
yield takeEvery(SUBMIT_USERNAME_PASSWORD, shootAPI);
}
// single entry point to start all Sagas at once
export default function* rootSaga() {
yield all([
watchSubmitBtn()
])
}
问题:
如何设置组件状态并将 push
发送到 url /companies
?在后端返回 200
之后?
最佳答案
我通常像传奇中那样处理条件导航。
现有代码的最简单答案是在 SUBMIT_USERNAME_PASSWORD 操作中将历史对象作为 Prop 传递,并在传奇成功案例中调用 history.push(),类似于:
const onSubmitClick = ({username, password}) => {
const { history } = this.props;
return {
type: SUBMIT_USERNAME_PASSWORD,
payload: {username, password, history}
};
};
.......
function* shootAPI(action){
try{
const res = yield call(shootApiTokenAuth, action.payload);
const { history } = action.payload;
yield put({
type: REQUEST_SUCCESS,
payload: res
});
history.push('/companies');
}catch(err){
yield put({
type: REQUEST_FAILED,
payload: err
});
}
}
关于javascript - redux saga 和 history.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47864755/