我有一个非常长的表格(确切地说是75输入),因为我使用redux来管理我的应用程序状态,每当我想编辑这个表单时,我想将表单的状态设置为支持以允许编辑
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>
}
}
上面的代码工作正常,问题是当这个组件安装时,它会给我错误"Cannot update during an existing state transition"
有时如果值没有在props中预定义,输入的值将是未定义的,所以在从服务器和更新组件加载道具后,我得到另一个错误&#34;尝试将输入从不受控制的变为控制的#34 ;那是因为this.state[name]
未定义,所以我得到了一个值
那么我做错了什么?如何将组件状态与props值链接,并确保如果props更改,状态也会发生变化,同时,如果状态发生变化,则不会影响道具。
答案 0 :(得分:4)
我希望修改您的代码以匹配以下逻辑将解决您的问题。在代码中查找注释以获取解释
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>);
}
}