【发布时间】: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)}
/>
)
}}
【问题讨论】:
-
你可以使用 shouldComponentUpdate。
-
每当一些props改变组件更新,你可以很容易地使用
prevProps和prevState那里看看developmentarc.gitbooks.io/react-indepth/content/life_cycle/… -
@VarunTheFalcon
shouldComponentUpdate完全是为了不同的目的
标签: javascript reactjs lifecycle