React动态添加员工输入框报employee.push is not a function求助
问题根源
- 报错
TypeError: employee.push is not a function是因为你更新employee状态的写法错误:setEmployee(...employee, value)会把原本是数组的employee直接覆盖为单个字符串/对象,导致下一次操作时调用push方法失效。 - 其次React的state是不可变数据,不能直接调用
employee.push修改原状态,必须通过setEmployee传入新数组更新。 - 另外你当前单字符输入就触发push的逻辑也有问题,会导致同一个输入框的内容多次重复插入数组。
修正方案
第一步:修改EmployeeName.js的逻辑
你已经在组件内维护了inputList存储所有输入框的内容,直接每次inputList变化时同步所有员工姓名到context即可,不用单独处理单个输入的push:
import { React, useState, useEffect } from "react"; import { Button, Form, Col, Row } from "react-bootstrap"; const EmployeeName = ({ employee, setEmployee}) => { const [inputList, setInputList] = useState([{ employee: "" }]); // 同步所有输入框的员工姓名到context的employee数组 useEffect(() => { // 提取所有非空的员工姓名,生成新数组更新状态 const empList = inputList.map(item => item.employee).filter(name => name.trim()); setEmployee(empList); }, [inputList, setEmployee]) const handleInputChange = (e, index) => { const { name, value } = e.target; const list = [...inputList]; list[index][name] = value; setInputList(list); }; const handleRemoveClick = (index) => { const list = [...inputList]; list.splice(index, 1); setInputList(list); }; const AddInputField = () => { setInputList([...inputList, { employee: "" }]); }; return ( <> <Button onClick={AddInputField}> 点击添加公司员工 </Button> {inputList.length > 0 && inputList.map((x, i) => { return ( <Row key={i}> <Col sm={11}> <Form.Group> <Form.Control placeholder="输入员工姓名" onChange={(e) => handleInputChange(e, i)} value={x.employee} name="employee" type="text" /> </Form.Group> </Col> <Col> {inputList.length - 1 === i ? ( <Button onClick={AddInputField} > 新增 </Button> ) : ( <Button onClick={() => handleRemoveClick(i)}>删除</Button> )} </Col> </Row> ); })} </> ); }; export default EmployeeName;
第二步:修正AddAccountsContxt.js里的提交逻辑
不要直接修改state原对象,也不要依赖set之后立刻获取state的旧值:
import React, { useState, createContext } from "react"; import axios from "axios"; export const AddAccountsContxt = createContext(); export const AddAccountsContxtProvider = (props) => { const [company, setCompany] = useState(""); const [address, setAddress] = useState(""); const [phone, setPhone] = useState(""); const [details, setDetails] = useState([]); const [employee, setEmployee] = useState([]); const addAccountHandler = (e) => { e.preventDefault(); // 生成新的details数组,不要直接修改原details const newDetails = [...details, { employee: employee }]; setDetails(newDetails); axios({ method: "POST", url: "http://localhost:5000/insert-form", data: { company: company, address: address, phone: phone, details: newDetails }, }); }; return ( <> <AddAccountsContxt.Provider value={[ company, setCompany, address, setAddress, phone, setPhone, employee, setEmployee, details, addAccountHandler, ]} > {props.children} </AddAccountsContxt.Provider> </> ); };
修改后不管新增多少个输入框,employee都会保持数组格式存储所有员工的姓名,提交时会完整把多姓名数据传到后端入库。
内容的提问来源于stack exchange,提问作者Julie
相关产品推荐
相关产品推荐

