You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router v6中props.match.params未定义错误求助

解决React Router v6中Uncaught TypeError: Cannot read properties of undefined (reading 'params')错误

问题原因

React Router v6彻底移除了通过组件props传递match、location等路由上下文对象的机制,所有路由相关数据都需要通过对应的Hook获取,这就是你调用props.match.params时出现undefined错误的核心原因。

修复步骤

  1. 导入useParams Hook:从react-router-dom中新增导入useParams
  2. 替换路由参数获取方式:用useParams()替代props.match.params
  3. 修正useEffect依赖项:将路由参数id加入依赖数组,确保参数变化时重新请求数据
  4. 修正状态初始值:将vfiInput的初始值从数组[]改为对象{},避免表单渲染时读取属性出错

修改后的完整代码

import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; // 新增useParams导入
import axios from 'axios';
import swal from 'sweetalert';

function EditVfi() { // 不再需要props参数

    const navigate = useNavigate();
    const { id: vfi_id } = useParams(); // 通过useParams获取路由id
    const [loading, setLoading] = useState(true);
    const [vfiInput, setVfi] = useState({}); // 初始值改为对象,而非数组
    const [errorInput, setError] = useState([]);

    useEffect(() => {   
        axios.get(`/api/edit-vfi/${vfi_id}`).then( res => {
            if(res.data.status === 200)
            {
                setVfi(res.data.vfi);
                setLoading(false);
            }
            else if(res.data.status === 404)
            {
                swal("Error",res.data.message,"error");
                navigate('/');
            }
        });
    }, [navigate, vfi_id]); // 新增vfi_id到依赖数组

    const handleInput = (e) => {
        e.persist();
        setVfi({...vfiInput, [e.target.name]: e.target.value });
    }

    const updateVfi = (e) => {
        e.preventDefault();
         
        const data = {
            Gender:vfiInput.Gender,
            firstName:vfiInput.firstName,
            secondName:vfiInput.secondName,
            MaritalStatus:vfiInput.MaritalStatus,
            TelNo:vfiInput.TelNo,
            TownofResidence:vfiInput.TownofResidence,
            Fellowshipifattendingany:vfiInput.Fellowshipifattendingany,
            MinistryInvolvedin:vfiInput.MinistryInvolvedin,
            ChurchYouattend:vfiInput.ChurchYouattend,
            Profession:vfiInput.Profession,
            LengthofMembershipinVFi:vfiInput.LengthofMembershipinVFi,
            Email:vfiInput.Email,
        }

        axios.put(`/api/update-vfi/${vfi_id}`, data).then(res=>{
            if(res.data.status === 200)
            {
                swal("Success",res.data.message,"success");
                setError([]);
                navigate('/');
            }
            else if(res.data.status === 422)
            {
                swal("All fields are mandetory","","error");
                setError(res.data.validationErrors);
            }
            else if(res.data.status === 404)
            {
                swal("Error",res.data.message,"error");
                navigate('/');
            }
        });
    }

    if(loading)
    {
        return <h4>Loading Vfi Data...</h4>
    }
    
    return (
        <div>
            <div className="row header-container justify-content-center">
                <div className="container-fluid mt-4">
                <div className="row justify-content-center">
              <section className="col-md-8">
                 <div className="card mb-3">
                     <h5 className="card-title">Update data of VFi Kenya Brethren</h5>
                            <div className="card-body">
                                <form onSubmit={updateVfi} >
                                   <div className="form-group">
                                        <label>Gender</label>
                                        <input type="text" name="Gender" onChange={handleInput} value={vfiInput.Gender || ''} className="form-control" /> {/* 加|| ''避免初始值为空时的警告 */}
                                        <span className="text-danger">{errorInput.Gender}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input type="text" name="firstName" onChange={handleInput} value={vfiInput.firstName || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.firstName}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Second Name</label>
                                        <input type="text" name="secondName" onChange={handleInput} value={vfiInput.secondName || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.secondName}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Marital Status</label>
                                        <input type="text" name="MaritalStatus" onChange={handleInput} value={vfiInput.MaritalStatus || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.MaritalStatus}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Tel No</label>
                                        <input type="text" name="TelNo" onChange={handleInput} value={vfiInput.TelNo || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.TelNo}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Town of Residence</label>
                                        <input type="text" name="TownofResidence" onChange={handleInput} value={vfiInput.TownofResidence || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.TownofResidence}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Fellowship</label>
                                        <input type="text" name="Fellowshipifattendingany" onChange={handleInput} value={vfiInput.Fellowshipifattendingany || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.Fellowshipifattendingany}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Ministry Involved in</label>
                                        <input type="text" name="MinistryInvolvedin" onChange={handleInput} value={vfiInput.MinistryInvolvedin || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.MinistryInvolvedin}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Church You Attend</label>
                                        <input type="text" name="ChurchYouattend" onChange={handleInput} value={vfiInput.ChurchYouattend || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.ChurchYouattend}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Profession</label>
                                        <input type="text" name="Profession" onChange={handleInput} value={vfiInput.Profession || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.Profession}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Length of Membership in VFi</label>
                                        <input type="text" name="LengthofMembershipinVFi" onChange={handleInput} value={vfiInput.LengthofMembershipinVFi || ''}  className="form-control" />
                                        <span className="text-danger">{errorInput.LengthofMembershipinVFi}</span>
                                    </div>
                                    <div className="form-group">
                                        <label>Email</label>
                                        <input type="text" name="Email" onChange={handleInput} value={vfiInput.Email || ''} className="form-control" />
                                        <span className="text-danger">{errorInput.Email}</span>
                                    </div>
                                    <button type="submit" className="btn btn-info">Update</button>
                                </form>

                            </div>
                        </div>
                        </section>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default EditVfi;

额外说明

  • 给表单输入框的value属性加上|| ''可以避免组件初始化时,因vfiInput为空对象导致的"controlled component"警告
  • 若你的路由定义中参数名不是id,需要对应修改useParams()解构的变量名,比如路由是/edit-vfi/:vfiId,则解构为const { vfiId: vfi_id } = useParams()

内容的提问来源于stack exchange,提问作者Brian Mweu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:20:42