我在我的应用开发中使用 React Electron Redux . 在另一种情况下,我能够从子组件更新父状态,但现在我无法做到,状态只是更新到子组件 .
我知道正在使用正确的值调用reducer动作,但 parent component 正在使用错误的(前一个)重新渲染,只有子组件的子树正在以正确的值呈现 .
我的方法:
我正在_1800543中创建一个函数(动作处理程序):
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)
并且此函数作为 prop 传递给子容器:
<Index focusOnSection={ this.props.focusOnSection }/>
最后,该方法在子视图中用作 onClick handler . 这不是使用 redux react 更新父级的正确方法吗?
2 回答
您必须将 this 上下文绑定到构造函数中的focusOnSection函数,否则它不知道 this 是什么 .
尝试将类似的构造函数添加到CreateExerciseCanvas:
这可能是使用ES6类最烦人的部分 .
如果在
focusOnSection (section)
中检查this.props
的值,您将看到它是undefined
. 这是因为focusOnSection () {}
是focusOnSection: function () {}
的短语法,它将this
绑定到函数,因此不再有this.props
.一种解决方案是将
this
硬绑定到构造函数中的类:另一个是使用像
focusOnSelection = () => {}
这样的箭头函数,它不绑定this
. 后一种解决方案仅适用于使用babel(检查es2015预设) .