【问题标题】:React child component not updating parent state反应子组件不更新父状态
【发布时间】:2017-09-10 20:15:53
【问题描述】:

我在我的应用开发中使用 React + Electron + Redux。在另一种情况下,我能够从子组件更新父状态,但现在我不能这样做,状态只会更新到子组件。

我知道reducer action是用正确的值调用的,但是父组件被错误的(前一个)重新渲染,只有子组件的子树是以正确的价值呈现。

我的方法:

我正在父组件容器中创建一个函数(动作处理程序):

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 + react 更新父级的正确方法吗?

【问题讨论】:

    标签: javascript react-redux


    【解决方案1】:

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

    尝试向您的 CreateExerciseCanvas 添加这样的构造函数:

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

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

    【讨论】:

    • 在我看来import CreateExerciseCanvas from '../../views/exercise/createExerciseCanvas'正在这样做,但是在将它也添加到容器之后,它也不起作用。
    • @Pedro,你为什么连接到容器而不是 CreateExerciseCanvas ?
    • 嗯,你是对的,我应该使用this.focusOnSection.bind(this),但它不起作用,即使进行了更改
    【解决方案2】:

    如果您检查focusOnSection (section) 中的this.props 的值,您将看到它是undefined。这是因为focusOnSection () {}focusOnSection: function () {}的简写语法,将this绑定到函数上,所以没有this.props

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

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

    另一个是使用箭头函数,如focusOnSelection = () =&gt; {},它不绑定this。后一种解决方案仅在您使用 babel 时才有效(检查 es2015 预设)。

    【讨论】:

    • this.props 已定义,并且正在以正确的值触发操作,如问题中所述,尽管容器正在以错误的值呈现。我应该在容器中使用 arrow 函数,如 吗?请注意,容器类正在扩展React.Component。您提出的 sintax 与 React.createClass 方法相关,该方法自上次更新以来已被弃用,我错了吗?
    • 您希望组件收到什么价值?我只能看到 focusOnSection 动作
    • 我的错误,我已将focusOnSection 方法更改为正确的sn-p,对此很抱歉,我收到了int value
    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2021-03-31
    • 2021-05-19
    相关资源
    最近更新 更多