reactjs 如何通过react中的onChange事件更改状态?

fslejnso  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(182)

我正在为CRUD应用程序的react frontend编写一个组件,该组件是一个允许更新数据库中记录的表单。首先,我用useState声明了state,但没有初始值

const [data, setData] = useState({})

其次,使用useEffect从后台获取数据

useEffect(
        function (){
            async function getEmployee(){
                const URL = `http://127.0.0.1:8888/api/payroll/${id}`
                try{

                    const res = await fetch(URL, {
                      method: 'GET',
                      headers: {
                          'Accept': 'application/json',
                          'Content-Type': 'application/json'
                      }
                    })
                    const list = await res.json()

                    setData(list)
                }catch(error){
                    console.log(error);
                }
            }
            getEmployee()
        }
    );

并将取到的数据设置为state,后端以json格式发送数据如下:

[{ "ID":1, "FIRSTNAME": "JOE", "SECONDNAME":"SMITH"}]

我有一个函数可以改变对象中特定元素的值

function handleChange(event){
        setData({...data, [event.target.name]: event.target.value});
    }

而是在object之外添加一个新值,例如:

[{ "ID":1, "FIRSTNAME": "JOE", "SECONDNAME":"SMITH"}, "SECONDNAME":"MARK"]

下面是我的react组件的所有代码:

import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import './form.css'

function Edit(props){

    const [data, setData] = useState({});

    const {id} = useParams();
    const navigate = useNavigate();

    useEffect(
        function (){
            async function getEmployee(){
                const URL = `http://127.0.0.1:8888/api/payroll/${id}`
                try{

                    const res = await fetch(URL, {
                      method: 'GET',
                      headers: {
                          'Accept': 'application/json',
                          'Content-Type': 'application/json'
                      }
                    })
                    const list = await res.json()

                    setData(list)
                }catch(error){
                    console.log(error);
                }
            }
            getEmployee()
        }, [props]
    );
        console.log(data);
    function handleSubmit(event){
        event.preventDefault();
        async function updateEmployee(){
            const URL = `http://127.0.0.1:8888/api/payroll/${id}`
            try{

                    const res = await fetch(URL, {
                      method: 'PATCH',
                      headers: {
                          'Accept': 'application/json',
                          'Content-Type': 'application/json'
                      },
                      body: JSON.stringify(data)
                    })
                    navigate(`/employee/${data.id}`);
            }catch(error){
                console.log(error);
            }
        }
        updateEmployee()
    }

    function handleChange(event){
        setData({...data, [event.target.name]: event.target.value});
    }

    function handleCancel(){
        navigate(`/employee/`);
    }

    return(
        <div className="container">
            <h1>Edytuj paracownika</h1>
            <hr />
            <form onSubmit={handleSubmit} className="form">
                <div className="form-group">
                    <label>FirstName</label>
                    <input
                        name="FIRSTNAME"
                        type="text"
                        required
                        value={data.FIRSTNAME}
                        onChange={handleChange}
                        className="form-control"
                    />
                </div>
                <div className="form-group">
                    <label>LastName</label>
                    <input
                        name="LASTNAME"
                        type="text"
                        required
                        value={data.LASTNAME}
                        onChange={handleChange}
                        className="form-control"
                    />
                </div>

                <div className="btn-group">
                    <input type="submit" value="Update" className="btn-submit"/>
                    <button
                        type="button"
                        onClick={handleCancel}
                        className="btn-submit"
                    >
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    )
}

export default Edit

和后端模块:

exports.getEmployeeById = async(req, res, next) => {

    let id = req.params.id;
    let query = `SELECT * FROM table_name WHERE ID = ${id}`;
    let connection;
    oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
    oracledb.autoCommit = true;

    try{
        connection = await oracledb.getConnection();
        const employee = await connection.execute(query)
        res.status(200).json(employee.rows)
    }catch(error){
        console.log(error);
        next(error)
    }

}
exports.updateEmployee = async(req, res, next) => {

    let id = req.params.id;

    let queryUpdate = `
    UPDATE table_name
    SET
    FIRSTNAME = '${req.body.FIRSTNAME}',
    FIRSTNAME = '${req.body.LASTNAME}',
    WHERE ID = ${id}
    `

    let connection;
    oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
    oracledb.autoCommit = true;

    try{
        connection = await oracledb.getConnection();
        const update = await connection.execute(queryUpdate);
        res.status(200).json({update})
    }catch(error){
        console.log(error);
        next(error)
    }

}

当然,我在控制器的底部导出这些模块。
我在想,这可能是错误的格式,我的数据从后端提取。我已经尝试使用JSON.stringify(data),但它不工作。

hc2pp10m

hc2pp10m1#

这是因为从端点返回的数据

[{ "ID":1, "FIRSTNAME": "JOE", "SECONDNAME":"SMITH"}]

不是对象而是数组。
如果你只想接收一个元素而不是一个数组,你必须更新你的端点返回一个对象,但是你可以只存储这个数组的第一个元素,它是一个对象:

setData(list[0])

然后:

setData({...data, [event.target.name]: event.target.value});

应按预期工作

相关问题