我有两个组成部分。子组件将在模式框中打开。模态框组件将包含添加和编辑用户。我为模态框输入传递了一些值,并在getDerivedStateFormProps生命周期挂钩中获取了该值。最初,它是将值填充为输入值。但是之后,如果在文本框中输入任何内容,状态将不会更新。请查看下面的详细信息
static getDerivedStateFromProps(props, state) {
state.show = props.show;
state.company = props.company;
return state;
}
onChange = async(e) => {
this.setState({company: {...this.state.company, [e.target.name]: e.target.value}});
}
但是状态没有更新。任何人都可以提供帮助来解决此问题。预先感谢。
答案 0 :(得分:0)
请勿更改state
参数。
getDerivedStateFromProps
的正确用法是返回一个浅合并到组件现有state
中的对象。
static getDerivedStateFromProps(props) {
const {show, company} = props;
return {show, company};
}
此外,{<1>}将由React 调用,然后将您的调用状态应用于getDerivedStateFromProps
。这意味着this.setState
中对company
的任何更改都会破坏getDerivedStateFromProps
中对company
的更改。