问题
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.
Code:
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;
}
}
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 ?
回答1:
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
;
Here are very basic examples of 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
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).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
Now
myAjaxLib.post("/someEndpoint", {data : someValue}).then()
in.then()
function you can check for the response if successfull the dispatch another action for egSAVE_USER_TO_SERVER_SUCCESS
otherwiseSAVE_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_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 ?
Answer: Not at all. Only three action mentioned above.
来源:https://stackoverflow.com/questions/53100829/how-to-make-a-post-request-using-react-redux