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

从深层组件触发onChange时出现props未定义的TypeError问题

解决「TypeError: Cannot read property 'props' of undefined」和值传递undefined的问题

看起来你在React+Redux+Redux Form的组合使用中遇到了几个典型的绑定和参数传递问题,我帮你逐个拆解解决:

1. 修复App组件中handleThis函数的this绑定问题

在类组件中,直接把类方法作为props传递给子组件时,默认会丢失this的指向,导致this.props变成undefined。有两种简洁的修复方式:

方式一:构造函数内绑定this

// App.js
class App extends Component {
 constructor(props) {
 super(props);
 // 绑定this,确保函数内的this指向App组件实例
 this.handleThis = this.handleThis.bind(this);
 }
 handleThis(value){
 // 调用Redux action并传递参数
 this.props.getPercent(value);
 }
 // ... 其他代码不变
}

方式二:用箭头函数定义类方法(更推荐)

箭头函数会自动绑定当前组件的this,省去手动绑定的步骤:

// App.js
class App extends Component {
 // 箭头函数自动绑定this
 handleThis = (value) => {
 this.props.getPercent(value);
 }
 // ... 其他代码不变
}

2. 修复DemoForm函数组件的this.props错误

DemoForm是函数组件,不存在this对象,你需要直接从props中解构出someFunction,而不是用this.props:

// Demo.js
// 直接解构props中的someFunction
let DemoForm = ({ handleSubmit, submitting, state, someFunction }) => (
 <form onSubmit={handleSubmit(showResults)}>
 {/* 直接调用someFunction,传递输入框的值 */}
 <Field name="value" label="Value" component={RenderInput} onChange={(e) => someFunction(e.target.value) } />
 <button type="submit"> Submit </button>
 {console.log("Demo state >>>>>>", {state})}
</form>
)
// ... 其他代码不变

3. 确保RenderInput传递onChange事件到输入框

你的RenderInput组件目前没有把onChange事件传递给底层input元素,导致输入变化无法触发上层回调。修改如下:

// RenderInput.js
// 接收onChange参数并传递给input
const RenderInput = createRenderer((input, label, { onChange }) => {
 return <input {...input} onChange={onChange}/>
})
export default RenderInput

或者更贴合Redux Form的用法:Redux Form的Field组件会自动把onChange、value等方法注入到input对象中,直接展开input即可:

// RenderInput.js
const RenderInput = createRenderer((input, label) => {
 // 直接展开input,包含Redux Form自动注入的所有属性和方法
 return <input {...input}/>
})
export default RenderInput

这种情况下,DemoForm的Field可以不用手动写onChange,而是在提交时从表单值中获取数据触发action:

// Demo.js
let DemoForm = ({ handleSubmit, submitting, state, someFunction, values }) => (
 <form onSubmit={handleSubmit((formValues) => {
 // 提交时获取表单值并触发action
 someFunction(formValues.value);
 showResults(formValues);
 })}>
 <Field name="value" label="Value" component={RenderInput} />
 <button type="submit"> Submit </button>
 {console.log("Demo state >>>>>>", {state})}
</form>
)

4. 修复Action中的拼写错误

你的getPercent action里把payload拼成了paypoad,导致值无法正确传递到reducer:

// ACTION.js
export function getPercent(value){
 console.log(value)
 // 修正拼写:paypoad → payload
 return { type: "GET_PERCENT", payload : value }
}

总结一下修改后的完整流程:

  1. App组件的handleThis正确绑定this,并调用Redux的getPercent action
  2. DemoForm作为函数组件,正确解构props中的someFunction
  3. RenderInput正确传递onChange事件(或使用Redux Form自动注入的方法)
  4. Action中的payload拼写修正

这样就能解决你遇到的「props未定义」和「值为undefined」的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:18:43