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
相关产品推荐
相关产品推荐

