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

React路由组件间传递Feature_ID时props出现undefined问题求助

问题分析与解决方案

核心问题

  1. 传递的ID非当前点击行ID:你在Edit_Features中给EditFeatureRow传递的key_id={this.state.Feature_ID}是固定取列表第一个元素的ID(data[0].featureID),而非点击行对应的ID。
  2. 路由跳转未携带目标ID:点击Edit链接时,没有把当前行的featureID传递到目标路由组件。
  3. componentDidUpdate无限循环:componentDidUpdate中直接调用DisplayFeatures,而DisplayFeatures会触发setState,进而再次触发componentDidUpdate,导致无限请求数据。
  4. Route组件使用错误:直接在Route内渲染EditFeatureRow并传递固定props,无法接收跳转时携带的动态ID。

修复步骤

步骤1:修复Edit_Features组件的路由与跳转逻辑

修改Link跳转时携带当前行的featureID,并调整Route配置,同时修复无限循环问题:

import React from "react";
import { Route, Link } from "react-router-dom";
import EditFeatureRow from './Edit_FeatureRow';

export class Edit_Features extends React.Component {
       constructor(props) {
              super(props);
              this.state = {
                     Feature: [],
                     loading: true,
              };
       }

       componentDidMount() {
              this.DisplayFeatures();
       }

       // 修复无限循环:仅当Feature数组长度变化时重新请求
       componentDidUpdate(prevProps, prevState) {
              if (prevState.Feature.length !== this.state.Feature.length) {
                     this.DisplayFeatures();
              }
       }

       DisplayFeatures() {
              fetch(REQUEST_URL)
                     .then(response => response.json())
                     .then((data) => {
                           this.setState({
                                  Feature: data,
                                  loading: false
                           })
                     })
                     .catch(error => console.error('Error:', error))
       }

       render() {
              return (
                     <div>
                            <form>
                                   {/* 修改Route,支持路由参数传递ID */}
                                   <Route path="/Edit_FeatureRow/:featureId" component={EditFeatureRow} />
                                   {this.state.loading ? (
                                          <div>加载中...</div>
                                   ) : (
                                          <table width="100%">
                                                 {this.state.Feature.map((item, index) => (
                                                        <tr key={index}>
                                                               <td>
                                                                      {/* 跳转时携带当前行的featureID作为路由参数 */}
                                                                      <Link to={`/Edit_FeatureRow/${item.featureID}`}> Edit</Link>
                                                               </td>
                                                               <td>{item.featureID}</td>
                                                               <td>{item.featureName}</td>
                                                        </tr>
                                                 ))}
                                          </table>
                                   )}
                            </form>
                     </div>
              );
       }
}
export default Edit_Features;

步骤2:修改Edit_FeatureRow组件获取路由参数

从路由参数中获取featureId,替代原来的props传递方式:

import React from "react";

export class Edit_FeatureRow extends React.Component {
       constructor(props) {
              super(props);
              this.state = {
                     Feature_ID: "",
                     FeatureName: "",
                     loading: true,
              };
              this.handleChange = this.handleChange.bind(this);
       }

       componentDidMount() {
              // 从路由参数中提取featureId
              const featureId = this.props.match.params.featureId;
              if (featureId) {
                     this.DisplayFeatureDetails(featureId);
              }
       }

       // 监听路由参数变化,切换编辑行时重新请求数据
       componentDidUpdate(prevProps) {
              const currentId = this.props.match.params.featureId;
              const prevId = prevProps.match.params.featureId;
              if (currentId !== prevId) {
                     this.DisplayFeatureDetails(currentId);
              }
       }

       DisplayFeatureDetails(featureId) {
              // 拼接ID到请求URL,适配后端接口
              fetch(`${REQUEST_URL}/${featureId}`, { 
                     headers: { "Content-Type": "application/json; charset=utf-8" }
              })
                     .then(response => response.json())
                     .then((data) => {
                           this.setState({
                                  Feature_ID: featureId,
                                  FeatureName: data[0].featureName,
                                  loading: false
                           })
                     })
                     .catch(error => console.error('Error:', error))
       }

       handleChange(event) {
              this.setState({ [event.target.name]: event.target.value });
       }

    render() {
        if (this.state.loading) {
               return <div>加载中...</div>;
        }
        return (                    
            <div>
                           <form>                                 
                                  <div>{this.state.Feature_ID} {this.state.FeatureName}</div> 
              </form>
             </div >
        );
   }
} 
export default Edit_FeatureRow;

额外说明

  • 若使用React Router v6,Route的写法需调整为<Route path="/Edit_FeatureRow/:featureId" element={<EditFeatureRow />} />,获取参数需用useParams钩子(需将组件改为函数组件或使用withRouter高阶组件)。
  • 确保后端接口支持根据featureId查询单条数据,fetch的URL需正确拼接ID。
  • 移除了Edit_Features中不必要的单条数据状态,列表渲染无需固定存储第一个元素的信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:33:25