React结构化State下父组件向子组件传空Props问题排查
问题解决方案
1. 修复state嵌套对象更新异常
你当前的handleChange直接用[name]作为键更新state,而name是current.excercise这类字符串,React会把它当成顶级属性新增到state中,而非更新current对象内部的属性。要解决这个问题,需要解析name的层级路径,针对性更新嵌套的current对象:
修改父组件的handleChange函数:
handleChange(event) { const target = event.target; const value = target.value; const [parentKey, childKey] = target.name.split('.'); // 拆分路径为父键和子键 // 先复制原current对象,避免直接修改state const updatedCurrent = { ...this.state.current }; updatedCurrent[childKey] = value; this.setState({ current: updatedCurrent }); }
这样就能正确更新state.current内部的属性,不会再出现独立的current.excercise这类顶级属性。
2. 解决handleSubmit中this.props为空的问题
你在父组件的handleSubmit里打印this.props,这里的this指向父组件App,如果App本身没有接收外部传入的props,打印结果自然是空对象。如果想查看子组件AddExcercise的props,需要在子组件调用handleSubmit时把自身props传过去:
第一步:修改子组件的表单提交事件
<form className='AddExcercise' onSubmit={(e) => this.props.handleSubmit(e, this.props)}>
第二步:修改父组件的handleSubmit函数接收参数
handleSubmit(event, childProps) { console.log('子组件props:', childProps); // 这里就能看到子组件的props了 let newExc = { excercise: this.state.current.excercise, muscle_part: this.state.current.muscle_part, weight: this.state.current.weight } let excercises = this.state.excercises.slice(); excercises.push(newExc); this.setState({excercises: excercises}); event.preventDefault(); }
如果你的本意不是查看子组件props,只是疑惑this.props为空,那属于正常情况——因为父组件App没有被传入任何props,所以this.props就是空对象。
额外优化建议
可以在父组件的构造函数里提前绑定方法,避免每次渲染子组件时重复执行bind:
constructor(props){ super(props); this.state = { excercises: [], current: { excercise: '', muscle_part: '', weight: '' } } // 提前绑定方法 this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
之后渲染子组件时就可以简化写法:
<AddExcercise handleSubmit={this.handleSubmit} handleChange={this.handleChange} excercise={this.state.current.excercise} muscle_part={this.state.current.muscle_part} weight={this.state.current.weight} />
内容的提问来源于stack exchange,提问作者Vlastimil Lisák
相关产品推荐
相关产品推荐

