首页 文章

通过props更新管理自己状态的组件

提问于
浏览
1

我有一个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 prop管理它所有关于更改的应用程序's own state and tell' .

该支柱基于路由安装:

<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 dispatch事件 . 发送给组件的道具将被更新,但它们将被忽略 . 它们仅用于在构造函数中设置组件状态 .

编辑:选择的答案是对的 . 在发布此问题之前我曾尝试过,但是去抖功能导致了一些奇怪的行为 .

1 回答

  • 0

    如果我理解正确,你想要在道具传递到组件更新时更新状态 .

    这最好在 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

相关问题