我有一个很长的表单(确切地说是 75 个输入),因为我使用 redux 来管理我的应用程序状态,每当我想编辑此表单时,我都想将表单的 State 设置为 prop 以允许编辑。
示例代码:
class VisitCard extends Component {
constructor(props) {
super(props); //props.visit = {name:'randome name', data:'etc..'}
this.state = Object.assign({},props.visit);
this.bindInput = this.bindInput.bind(this);
}
//BindInput will return props for Inputs, to achive two way binding
bindInput(config){
const {name,...props} = config;
return {
value : this.state[name],
onChange: event => this.setState({[name]:event.target.value}),
...props
}
}
render(){
return <div>
<input {...this.bindInput({name:'name', type:'text'})} />
<input {...this.bindInput({name:'data', type:'text'})} />
</div>
}
}
上面的代码工作完美,问题是当这个组件安装时,它给我错误“无法在现有状态转换期间更新”
有时,如果 Prop 中未预定义该值,则输入的值将是未定义的,因此在从服务器加载 Prop 并更新组件后,我会收到另一个错误“尝试将输入从不受控制更改为受控制”,这是因为this.state[name]
未定义,然后我得到了一个值
那么我做错了什么?我如何将组件的状态与 props 值链接起来,并确保如果 props 改变,state 也会改变,而同时,如果状态改变,这不会影响 props。
最佳答案
我希望修改您的代码以匹配以下逻辑将解决您的问题。查找代码中的注释以获取解释
class VisitCard extends Component {
constructor(props) {
super(props);
//set your state to have a key that holds your prop value.
this.state = { visit: props.visit };
this.bindInput = this.bindInput.bind(this);
}
componentWillReceiveProps(nextProps) {
//if your props is received after the component is mounted, then this function will update the state accordingly.
if(this.props.visit !== nextProps.visit) {
this.setState({visit: nextProps.visit});
}
}
bindInput(config){
const {name,...props} = config;
// return defaultValue which you get from the props.
// you can add `value: this.state.visit[name]` to the below object only if you want your input to be controlled, else it can be ignored.
return {
defaultValue : this.props.visit[name],
onChange: event => this.setState(
{visit: { ...this.state.visit,
[name]:event.target.value}
}),
...props
}
}
render(){
// render empty if your props has not yet arrived.
if(!this.props.visit) {
return (<div />);
}
// render after you have values in props
return (<div>
<input {...this.bindInput({name:'name', type:'text'})} />
<input {...this.bindInput({name:'data', type:'text'})} />
</div>);
}
}
关于javascript - 将状态与 props 同步,实现 ReactJS 中表单输入的双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498682/