如何使用React Redux发出发布请求?

时间:2018-11-01 11:57:00

标签: reactjs redux axios redux-thunk

我创建了一个包含电子邮件,名字,姓氏详细信息的表单。现在,我想向localhost:5000/api/users发出POST请求,并将其存储在mongo数据库中。如何使用redux?我已经在reactjs上实现了它,但是我只能使用redux吗?注意:我正在使用redux thunk。

代码:

login.js:

import React, { Component } from 'react'
import './login.css'

export default class Login extends Component {

  constructor(props) {
    super(props)
    this.state = {
      firstName:'',
      lastName:'',
      email:''
    }

    this.onChangeHandler = this.onChangeHandler.bind(this)
    this.onSubmitHandler = this.onSubmitHandler.bind(this)
  }

  onChangeHandler(e){
    this.setState({ [e.target.name]: e.target.value })
  }

  onSubmitHandler(e){
    e.preventDefault();
    console.log(this.state)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.onSubmitHandler}>
          <label>
            FirstName:
            <input type="text" name="firstName" value={this.state.firstName} onChange={this.onChangeHandler} />
          </label>

          <label>
            LastName:
            <input type="text" name="lastName" value={this.state.lastName} onChange={this.onChangeHandler} />
          </label>

          <label>
            Email:
            <input type="text" name="email" value={this.state.email} onChange={this.onChangeHandler} />
          </label>
          <button type="submit" className="btn btn-default">Submit</button>
        </form>
      </div>
    )
  }
}

loginAction.js:

import { ADD_USER } from './types';
import axios from 'axios';

export const userLoginRequest = () => dispatch => {
    axios.post(`localhost:5000/api/users`)
    .then( userdata => 
        dispatch({
            type: ADD_USER,
            payload: userdata
        })
    )
    .catch( error => {
        console.log(error);
    });
};

loginReducer.js:

import { ADD_USER } from '../actions/types';

const initialState = {
    firstName: '',
    lastName: '',
    email: ''
}


export default function (state = initialState, action) {
    switch (action.type) {
        case ADD_USER:
            return {
                ...state,
                items: action.payload
            };
        default:
            return state;
    }
}

我无法理解我是否需要针对名字,姓氏和电子邮件分别创建3个动作?在那种情况下,这3个动作将是3个,每个动作都有3个POST请求?

1 个答案:

答案 0 :(得分:1)

我建议您对reduxredux-thunk有一些了解。 为了发出网络请求,您需要使用redux-thunkredux-saga等中间件;

以下是redux-thunk

的非常基本的示例
//example 1
function myThunkActionCreator(someValue) {
    return (dispatch, getState) => {
        dispatch({type : "REQUEST_STARTED"});

        myAjaxLib.post("/someEndpoint", {data : someValue})
            .then(
                response => dispatch({type : "REQUEST_SUCCEEDED", payload : response}),
                error => dispatch({type : "REQUEST_FAILED", error : error})
            );    
    };
}

// example 2 for conditional dispatching based on state
const MAX_TODOS = 5;

function addTodosIfAllowed(todoText) {
    return (dispatch, getState) => {
        const state = getState();

        if(state.todos.length < MAX_TODOS) {
            dispatch({type : "ADD_TODO", text : todoText});
        }    
    }
}

更新

因此,使用redux-thunk将表单数据发布到服务器的流程就像这样

  1. 当单击“提交”按钮并调度操作时,让我们假设SAVE_USER_TO_SERVER并将具有所有用户详细信息(名称,电子邮件等)的对象传递给postUserThunkCreator()(像上面示例中的thunk函数)。

  2. 然后thunk向服务器发出发布请求,并将数据与之一起发送。然后在服务器端将其保存到数据库中并返回响应

  3. 现在在myAjaxLib.post("/someEndpoint", {data : someValue}).then()函数中的.then()中,您可以检查响应是否成功,例如为SAVE_USER_TO_SERVER_SUCCESS分配另一个动作,否则可以SAVE_USER_TO_SERVER_FALIURE

    < / li>

*因此,正如我们所看到的,在此工作流程中已分担了三个动作: SAVE_USER_TO_SERVER

SAVE_USER_TO_SERVER_SUCCESS

SAVE_USER_TO_SERVER_FALIURE

因此,我希望您能明确地说出要创建上述三个动作。

您的问题 我是否需要针对名字,姓氏和电子邮件分别创建3个动作?

答案:完全没有。上面只有三个动作。

相关问题