我试图将action.payload分配给状态记录的用户,但是当我在控制台日志中打印记录的用户时,它返回未定义的状态。
这是action.payload数据:
{
id: 1,
firstname: "Leanne",
lastname: "Gram",
password: "123",
phone: "9474211442"
}
action.payload的数据类型为: 对象 ,如果将其更改为字符串,则输出保持不变。
这是console.log(this.state.loggeduser)的输出:
{}
handleSubmit = (dispatch, e) => {
const firstname = this.state.Firstname;
const password = this.state.password;
const datas = {
firstname, password //
}
alert(this.state.Firstname)
e.preventDefault();
axios.post('http://localhost:3001/login', datas).then(response => dispatch({
type: 'ADD_DETAILS',
payload: (response.data[0])
})
)
}
import React, {Component} from 'react'
import axios from 'axios'
const Context = React.createContext();
const reducer = (state, action) => {
console.log("From switch")
console.log(action.payload)
switch (action.type) {
case 'ADD_DETAIL':
return {
...state,
Loggeduser: [action.payload, ...state.Loggeduser]
};
default:
return state;
}
}
export class Provider extends Component {
state = {
posts: [],
Loggeduser: [
{}
],
dispatch: action => this.setState(state => reducer(state, action))
};
render() {
return (
< Context.Provider
value = {this.state} >
{console.log("From main")}
{
console.log(this.state.Loggeduser)
}
{
this.props.children
}
<
/Context.Provider>
)
}
}
export const Consumer = Context.Consumer;