![](/img/trans.png)
[英]Updating Parent component state from Child component TextInput in React Native
[英]React child component not updating parent state
我在应用程序开发中使用React + Electron + Redux 。 在另一种情况下,我能够从子组件更新父状态,但是现在我无法执行此操作,该状态仅被更新为子组件。
我知道用正确的值调用reducer动作,但是使用错误的一个(上一个)重新渲染父组件 ,而使用正确的值仅渲染子组件的子树。
我在父组件容器中创建一个函数(动作处理程序):
class CreateExerciseCanvas extends React.Component {
focusOnSection (section) { /* this is the function that i'm refering to */
store.dispatch(actions.focusOnSection(section))
}
render() {
return (
<CreateExerciseCanvas
focusOnSection={ this.focusOnSection }
/>
)
}
}
const mapStateToProps = function (store) {
return {
focusOnSection: store.exercise.focusOnSection
}
}
export default connect(mapStateToProps)(CreateExerciseCanvasContainer)
此功能作为道具传递给子容器:
<Index focusOnSection={ this.props.focusOnSection }/>
最后,该方法在子视图中用作onClick处理程序 。 这不是用redux + react更新父母的正确方法吗?
您必须将此上下文绑定到构造函数中的focusOnSection函数,否则它将不知道这是什么。
尝试向您的CreateExerciseCanvas添加类似的构造函数:
constructor(props) {
super(props);
this.focusOnSection = this.focusOnSection.bind(this);
}
这可能是关于使用ES6类的最烦人的部分。
如果在focusOnSection (section)
检查this.props
的值,您将看到它是undefined
。 这是因为focusOnSection () {}
是短语法focusOnSection: function () {}
这是结合this
的功能,所以没有更多this.props
。
一个解决办法是硬约束this
在构造方法的类:
constructor(props) {
super(props);
this.focusOnSection = this.focusOnSection.bind(this);
}
另一个将使用诸如focusOnSelection = () => {}
类的箭头函数,该函数不绑定this
。 后一种解决方案仅在使用babel时有效(请检查es2015预设)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.