【问题标题】:How to update state when props changes道具更改时如何更新状态
【发布时间】:2019-02-18 12:16:46
【问题描述】:

我有一个父组件,它呈现一个大表单。 父组件具有呈现输入的子组件 Child1 - Child4。

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

我需要像 componentWillReceiveProps 这样的东西, 仅在更改时根据 Parent.props 计算新的 Parent.state。

我不能使用 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】:

有两种选择:

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

减号:如果 props 发生变化,组件会重新渲染两次。 另一种选择:

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

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

【讨论】:

  • 它打破了函数的“单一职责原则”。它应该只做一个布尔检查,但它也在做其他事情。那么 componentDidUpdate(..) 呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 2021-12-14
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多