【问题标题】:Updating a component that manages its own state via props更新通过 props 管理自身状态的组件
【发布时间】:2017-07-28 10:04:02
【问题描述】:

我有一个 react/redux 应用程序。通常,所有状态更改都应通过 redux 处理,但对于似乎不起作用的输入。所以我有一个管理输入的组件,这是它的构造函数:

constructor(props) {
    super(props);

    // Bind functions now
    this.changeSlider = this.changeSlider.bind(this);
    this.changeFromInput = this.changeFromInput.bind(this);
    this.getValue = this.getValue.bind(this);

    this.state = {
        min: props.min,
    }
}

一旦组件被挂载,它就会管理自己的状态,如下所示:

changeSlider(e) { // input's onClick is binded to this function
    let val = parseInt(e.target.value,10);
    this.setState(_.merge({}, this.state, { min: val })); 
    // update redux state
    _.debounce(this.props.onChange, 50)(val);
}

所以组件管理它自己的状态,并通过onChange 属性告诉应用程序有关更改的其余部分。

这个道具是根据路由挂载的:

<Router history={browserHistory}>
    <Route path="/" component={App}>
        <IndexRedirect to="/Path/1" />    
        <Route path="Path" component={Container}>
            <Route path="1" component={Component} />
            <IndexRedirect to="1" />
        </Route> 
    </Route>
</Router>    

Container 负责从查询字符串中抓取状态:

// in Container
componentWillMount() {
    let {min} = this.props.location.query;
    this.props.actions.changeMin(min);
}

Container 然后将一些道具传播到它的孩子身上,并渲染它们。

如果我访问/Path/1?min=123123,组件会被挂载,然后在 componentWillMount() 中触发 redux 调度事件。发送到组件的道具将被更新,但它们将被忽略。它们仅用于在构造函数中设置组件状态。

编辑:选择的答案是正确的。在发布这个问题之前我已经尝试过了,但是去抖动功能导致了一些奇怪的行为。

【问题讨论】:

  • 不太清楚你的问题是什么

标签: reactjs redux


【解决方案1】:

如果我理解正确,您希望在传递到组件的道具更新时更新状态。

这最好在componentWillReceiveProps 生命周期方法中完成。

constructor(props) {
    super(props);

    // Bind functions now
    this.changeSlider = this.changeSlider.bind(this);
    this.changeFromInput = this.changeFromInput.bind(this);
    this.getValue = this.getValue.bind(this);

    this.state = {
        min: props.min,
    }
}

// Add this method
componentWillReceiveProps(nextProps) {
    this.setState({
        min: nextProps.min,
    })
}

文档:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

【讨论】:

  • 我试过这个,但没有用,但我发现了问题。一位同事添加了_.debounce 可能会减少动作噪音。这会延迟消息的执行并导致一些奇怪的竞争条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2018-11-23
  • 2021-01-07
  • 2019-07-14
  • 1970-01-01
  • 2022-11-16
相关资源
最近更新 更多