为什么赢得Axios会给我一个Redux动作的回应?

时间:2017-08-30 04:09:05

标签: reactjs asynchronous react-redux redux-form axios

我正在尝试制作一个简单的注册表单。我有一个redux表单,我试图将一些用户数据发送到我的快递后端。我试图通过redux动作通过redux动作来做到这一点:

最终,我希望收到回复,并在必要时重定向或提供错误。后端似乎接收数据并且可以验证,但是接收响应的axios让redux知道更新状态。有什么想法吗?

编辑:我也尝试将axios请求放在signupForm本身内部,但仍然存在问题(无法获得响应)。

修改:如果您想查看所有文件,请参阅以下内容:https://github.com/capozzic1/react-blog

redux注册操作

import axios from 'axios';
import { SubmissionError } from 'redux-form';


/* eslint-disable */
export const signUp = userData => dispatch => axios.post('/api/users', userData)
.then((response) => {
  dispatch({ type: 'SIGNUP_REDIRECT_YES ', payload: true})
  // this.props.history.go('/');
  console.log(response);
})
.catch((error) => {
  console.log(error.response);
  dispatch({ type: 'SIGNUP_REDIRECT_NO ', payload: false})
  throw new SubmissionError({ _error: 'Login failed!' });
});

注册表单组件(redux-form):

class SignUpForm extends React.Component {
  constructor(props) {
    super(props);

    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(userData) {
    this.props.signup(userData);

  }

  render() {
    const { error, handleSubmit, pristine, reset, submitting } = this.props;
    return (
      <form >
        {error && (<strong>{error}</strong>)}
        <Field name="username" type="text" component={renderField} label="Username" />
        <Field name="email" type="email" component={renderField} label="Email" />
        <Field name="password" type="text" component={renderField} label="Password" />
        <Field name="passwordConfirm" type="text" component={renderField} label="Enter password to confirm" />

        <div>
          <button type="button" disabled={submitting} onClick={handleSubmit(this.onSubmit)}>Sign Up</button>
          <button type="button" onClick={reset}>Clear Values</button>
        </div>
      </form>
    );
  }
}


export default reduxForm({
  form: 'signUpForm',


})(SignUpForm);

这个表格由一个容器组件提供(认为这是一个标准模式?如果不是,请告诉我)。  注册页面容器:

const mapDispatchToProps = dispatch => ({
  signup: (user) => {
    dispatch(signUp(user));
  },
});
const SignUp = props => (
  <Layout>
    <SignUpForm signup={props.signup} />;
  </Layout>
);

export default connect(null, mapDispatchToProps)(SignUp);

以下是注册缩减器:

export default function reducer(state = {
  signupRedirect: false,
}, action) {
  switch (action.type) {
    case 'SIGNUP_REDIRECT_YES': {
      return {
        ...state, signupRedirect: action.payload,
      };
    }
    case 'SIGNUP_REDIRECT_NO' : {
      return {
        ...state, signupRedirect: action.payload,
      };
    }
  }

  return state;
}

这是我的商店

import { applyMiddleware, createStore, compose } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import reducer from './reducers';


const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
  applyMiddleware(promise(), thunk, createLogger()),
));

export default store;

1 个答案:

答案 0 :(得分:1)

它不起作用,因为signUp函数返回的匿名函数返回一个promise。使用括号可以避免默认行为。

export const signUp = userData => dispatch => {
  axios.post('/api/users', userData)
    .then((response) => {
      dispatch({ type: 'SIGNUP_REDIRECT_YES ', payload: true})
      // this.props.history.go('/');
      console.log(response);
    })
    .catch((error) => {
      console.log(error.response);
      dispatch({ type: 'SIGNUP_REDIRECT_NO ', payload: false})
      throw new SubmissionError({ _error: 'Login failed!' });
    });
  }