无法将对象添加到数组中



我是react hooks和redux的新手,我正在构建简单的CRUD Employee应用程序,当我尝试添加员工时,它会显示为null。这意味着它显示在数组中,但它是空白的。

这是我的密码。

import React, {useState, useEffect} from 'react';
import {Form, Button} from 'react-bootstrap';
import {useHistory} from 'react-router-dom'
import {addEmployee} from "../../actions/employeeActions";
import FormContainer from "../layout/FormContainer";
import {useDispatch} from "react-redux";
const AddEmployee = () => {
let history = useHistory()
const dispatch = useDispatch()
const [full_name, setFull_name] = useState('');
const [email, setEmail] = useState('');
const [phone_number, setPhone_number] = useState('');
const [address, setAddress] = useState('');
const onSubmit = (e) => {
e.preventDefault()
dispatch(addEmployee())
history.push('/home')
}

和减速器。

case ADD_EMPLOYEE:
return {
...state,
employees: [action.payload, ...state.employees],
loading: false
}

和行动。

export const addEmployee = () => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const response = await axios.post('api/employees', config)
dispatch({
type: ADD_EMPLOYEE,
payload: response.data
})
}

请协助

当您dispatch(addEmployee())时,您甚至不会将参数(例如姓名、电子邮件、电话…(传递给action.js中的addEmployee。这就是你得到null回报的原因。

试试这个:

export const addEmployee = (name, email, phone, address) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
},
// post the params as data in your axios call
data: JSON.stringify({ name, email, phone, address })
}
const response = await axios.post('api/employees', config)
dispatch({
type: ADD_EMPLOYEE,
payload: response.data
})
}

然后调度

dispatch(addEmployee(full_name, email, phone_number, address));

编辑:

由于状态在调度操作之前仍然出现null(在onSubmit()中(,这意味着状态在调度之前不会更新。尝试更新您的代码如下:

<input value={full_name} onChange={(e) => setFull_name(e.target.value)} />

相关内容

  • 没有找到相关文章