我创建了一个包含电子邮件、名字、姓氏详细信息的表单。现在我想向 POST 请求localhost:5000/api/users
并将其存储在 mongo 数据库中。如何使用 redux ?我只在 reactjs 上使用了它,我该如何使用 redux ?注意:我使用的是 redux thunk。
代码:
登录.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>
)
}
}
登录Action.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 个 POST 请求?