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

React父子组件传值时报Cannot read properties of undefined (reading 'props') 如何解决

问题原因
  • 子组件Dropdown是函数式组件,React函数式组件中不存在this关键字,直接调用this.props自然会触发Cannot read properties of undefined (reading 'props')报错。
  • 父组件传递给子组件的自定义事件名是onDropdown,但子组件中调用的是this.props.handlePractice,prop名完全不匹配,即便解决this问题也找不到对应方法。
  • 父组件的handlePractice是普通函数定义,没有绑定this指向,就算子组件成功触发方法,方法内部访问this.setState也会抛出报错。
修复步骤

1. 修改子组件代码

函数式组件通过入参接收props,直接使用入参调用父组件传递的方法即可,代码修改后如下:

import React,{useState} from 'react';
import SEPractices from "../dummydata/SEPractices"

const optionItems = SEPractices.map((SEPractice) =>
  <option key={SEPractice.practice}>{SEPractice.practice}</option>
);
// 函数组件接收props作为参数
const Dropdown = (props) => {
  const [selectValue, setValue] = useState("")
    
  const handleSelect = (e) => {
    console.log(e.target.value);
    setValue(e.target.value);
    // 去掉this,用接收的props调用,方法名和父组件传递的onDropdown保持一致
    props.onDropdown(e.target.value);
  }

  return (
    <div>
      <select value={selectValue} onChange={handleSelect}> 
        <option value="dummyData">
          Select an SE Practice
        </option>
        {optionItems}
      </select>
    </div>
  )
}
export default Dropdown;

2. 修改父组件代码

将handlePractice改为箭头函数,绑定this指向当前组件实例,修改对应代码块如下:

// 把普通函数改为箭头函数,自动绑定this指向当前组件实例
handlePractice = (Option) => {
  console.log("hi");
  axios.get(`https://localhost:5000/api/articles/${Option}`)
  .then((response) =>{
    const data = response.data;
    this.setState({dbArticles: data});
    console.log('state', this.state);
  })
  .catch(()=>{
    alert('error retrieving data');
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:15:04