简体   繁体   English

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

[英]How to make a post request using react redux?

I have created a form with email, firstname, lastname details. 我创建了一个包含电子邮件,名字,姓氏详细信息的表单。 Now I want to make a POST request to localhost:5000/api/users and want to store it in mongo database. 现在,我想向localhost:5000/api/users发出POST请求,并将其存储在mongo数据库中。 How can I make use of redux ? 如何使用redux? I have implemented it using on reactjs only how can I make use of redux ? 我已经在reactjs上实现了它,但是我只能使用redux吗? Note: I am using redux thunk. 注意:我正在使用redux thunk。

Code: 码:

login.js: 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: 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: 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;
    }
}

I am not able to understand do I need to create 3 actions each one for firstname, lastname and email ? 我不明白我是否需要针对名字,姓氏和电子邮件分别创建3个动作? In that case what will be those 3 actions will it have 3 POST req in each of them ? 在那种情况下,这3个动作将是3个,每个动作都有3个POST请求?

I recommend you to have some insight about redux and redux-thunk . 我建议您对reduxredux-thunk有一些了解。 For making network requests you need to use middleware like redux-thunk or redux-saga ; 为了发出网络请求,您需要使用redux-thunkredux-saga类的中间件;

Here are very basic examples of redux-thunk 这是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});
        }    
    }
}

Update 更新

So the flow for posting the form data to the server using redux-thunk goes like so 因此,使用redux-thunk将表单数据发布到服务器的流程如下

  1. When submit button is clicked and action gets dispatched let us suppose SAVE_USER_TO_SERVER and an object with all the user details (name, email etc) is passed to for eg postUserThunkCreator() (which is a thunk function like in examples above). 当单击提交按钮并分派操作时,让我们假设SAVE_USER_TO_SERVER以及一个包含所有用户详细信息(名称,电子邮件等)的对象将传递给例如postUserThunkCreator() (这是一个类似于上面示例中的thunk函数)。

  2. Then thunk makes a post request to the server and sends the data along with it. 然后thunk向服务器发出发布请求,并将数据与之一起发送。 And on the server side it gets saved into the database and response is returned 在服务器端,它被保存到数据库中并返回响应

  3. Now myAjaxLib.post("/someEndpoint", {data : someValue}).then() in .then() function you can check for the response if successfull the dispatch another action for eg SAVE_USER_TO_SERVER_SUCCESS otherwise SAVE_USER_TO_SERVER_FALIURE ; 现在, myAjaxLib.post("/someEndpoint", {data : someValue}).then().then()函数中,您可以检查响应是否成功,例如为SAVE_USER_TO_SERVER_SUCCESS调度另一个动作,否则为SAVE_USER_TO_SERVER_FALIURE

*So as we can see that three actions are bieng dipatched in this work flow namely : SAVE_USER_TO_SERVER *因此,我们可以看到在该工作流程中已分担了三个动作: SAVE_USER_TO_SERVER

SAVE_USER_TO_SERVER_SUCCESS

SAVE_USER_TO_SERVER_FALIURE

So I hope its clear to you that you to create three action mentioned above. 因此,我希望您清楚您要创建上述三个操作。

Your Question Do I need to create 3 actions each one for firstname, lastname and email ? 您的问题我是否需要针对名字,姓氏和电子邮件分别创建3个动作?

Answer: Not at all. 答:完全没有。 Only three action mentioned above. 上面只有三个动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM