如何使用React Redux发出发布请求? [英] How to make a post request using react redux?
问题描述
我创建了一个包含电子邮件,名字,姓氏详细信息的表单.现在,我想向localhost:5000/api/users
发出POST请求,并将其存储在mongo数据库中.如何使用redux?我已经在reactjs上实现了它,但是我只能使用redux吗?注意:我正在使用redux thunk.
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. How can I make use of redux ? I have implemented it using on reactjs only how can I make use of redux ? Note: I am using 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:
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;
}
}
我无法理解我是否需要针对名字,姓氏和电子邮件分别创建3个动作?在那种情况下,这3个动作将是3个,每个动作都有3个POST请求?
I am not able to understand do I need to create 3 actions each one for firstname, lastname and email ? In that case what will be those 3 actions will it have 3 POST req in each of them ?
推荐答案
我建议您对redux
和redux-thunk
有一些了解.
为了发出网络请求,您需要使用redux-thunk
或redux-saga
;
I recommend you to have some insight about redux
and redux-thunk
.
For making network requests you need to use middleware like redux-thunk
or redux-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
将表单数据发布到服务器的流程是这样的
So the flow for posting the form data to the server using redux-thunk
goes like so
-
当单击提交"按钮并调度动作时,让我们假设
SAVE_USER_TO_SERVER
并将具有所有用户详细信息(名称,电子邮件等)的对象传递给例如postUserThunkCreator()
(这是一个类似thunk的功能)在上面的示例中).
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 egpostUserThunkCreator()
(which is a thunk function like in examples above).
然后thunk向服务器发出发布请求,并将数据与之一起发送.并在服务器端将其保存到数据库中并返回响应
Then thunk makes a post request to the server and sends the data along with it. And on the server side it gets saved into the database and response is returned
现在在.then()
函数中的myAjaxLib.post("/someEndpoint", {data : someValue}).then()
中,您可以检查是否成功分配了另一个操作,例如SAVE_USER_TO_SERVER_SUCCESS
否则为SAVE_USER_TO_SERVER_FALIURE
;
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
;
*因此,正如我们所看到的,在此工作流程中已分担了三个动作:
SAVE_USER_TO_SERVER
*So as we can see that three actions are bieng dipatched in this work flow namely :
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.
您的问题 我是否需要针对名字,姓氏和电子邮件分别创建3个动作?
Your Question Do I need to create 3 actions each one for firstname, lastname and email ?
答案:完全没有.上面只有三个动作.
Answer: Not at all. Only three action mentioned above.
这篇关于如何使用React Redux发出发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!