React子组件不更新父状态

时间:2017-04-14 14:41:15

标签: javascript react-redux

我在我的应用开发中使用 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)

此函数作为 prop 传递给子容器:

<Index focusOnSection={ this.props.focusOnSection }/>

最后,该方法在子视图中用作 onClick处理程序。 这不是用 redux + 反应来更新父级的正确方法吗?

2 个答案:

答案 0 :(得分:0)

您必须将上下文绑定到构造函数中的focusOnSection函数,否则它不知道是什么。

尝试将类似的构造函数添加到CreateExerciseCanvas:

constructor(props) {
    super(props);
    this.focusOnSection = this.focusOnSection.bind(this);
}

这可能是使用ES6类最烦人的部分。

答案 1 :(得分:0)

如果您在this.props内查看focusOnSection (section)的值,您会看到它是undefined。这是因为focusOnSection () {}focusOnSection: function () {}的短语法,它将this绑定到函数,因此不再有this.props

一个解决方案是将this硬绑定到构造函数中的类:

constructor(props) {
    super(props);
    this.focusOnSection = this.focusOnSection.bind(this);
}

另一个是使用focusOnSelection = () => {}之类的箭头函数,它不会绑定this。后一种解决方案仅适用于使用babel(检查es2015预设)。

相关问题