道具改变时如何更新状态

问题描述 投票:0回答:1

我有一个组件Parent,它呈现一个大的形式。父组件具有表示子组件Child1 - Child4,它们呈现输入。

当Parent.props发生变化时,Child1 - Child4的值应从props中删除为默认值。用户必须能够通过父方法更改ChildN值。

我需要类似componentWillReceiveProps的东西来计算新的Parent.state,它取决于Parent.props只在它发生变化时。

我不能使用getDerivedStateFromProps,因为我需要访问旧道具和新道具。 getDerivedStateFromProps仅允许访问新道具。我不想使用componentWillReceiveProps。

class Parent extends Component {
state = {
    value: Object.assign({}, this.props.value)
};
handleInputChange(event) {
    this.setState({
        value: event.currentTarget.value
    });
}
render() {
    return (
        <Child
            onChange={this.handleInputChange.bind(this)}
            value={this.state.value}/>

    )
}}class Child extends Component {
render() {
    return (
        <input type="text"
           name="input"
           value={this.props.value}
           onChange={this.props.onChange.bind(this)}
        />

    )
}}
javascript reactjs lifecycle
1个回答
0
投票

有两种选择:

shouldComponentUpdate(nextProps, nextState) {
if (this.props.value.id !== nextProps.value.id) {
    this.setState({
        value: Object.assign({}, nextProps.value)
    });
}
return true;}

减号:如果道具发生变化,组件会重新渲染两次。另外一个选项:

shouldComponentUpdate(nextProps, nextState) {
if (this.props.value.id !== nextProps.value.id) {
    this.state.value: Object.assign({}, nextProps.value)
}
return true;}

减:直接变异,但已经调用了render()。我不喜欢这两个选项(并使用componentDidUpdate),它们看起来不是最佳实践。

© www.soinside.com 2019 - 2024. All rights reserved.