我有一个表单,其中包含一些需要根据状态值预先填写的字段。
问题实际上是,当我仅记录道具时,我可以找到带有所有必要数据的Schema对象,但是当我记录状态时,它似乎未定义。
我尝试使用ComponentWillReceiveProps
将道具传递到我的状态,但是没有用,也许我滥用了它。
在这种情况下我应该使用哪种方法?
constructor(props) {
super(props);
this.state = {
display_name: this.props.Schema.display_name,
phone: this.props.Schema.phone,
email: this.props.Schema.email,
activated: this.props.Schema.activated,
groups: this.props.Schema.groups
}
console.log(props);
console.log("state", this.state)
this.editUser = this.editUser.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
var target = event.target;
this.setState({
[target.name]: target.value
})
console.log(this.state);
}
<input type={i.type}
defaultValue={this.state.display_name}
name={this.state.display_name}
id={this.state.id}
onChange={this.handleChange}
/>
答案 0 :(得分:0)
您是否尝试过直接在类主体中使用状态?
state = {
display_name: this.props.Schema.display_name,
phone: this.props.Schema.phone,
email: this.props.Schema.email,
activated: this.props.Schema.activated,
groups: this.props.Schema.groups
}
编辑
尝试这样的willReceiveProps吗?
componentWillReceiveProps(nextProps) {
if (!_.isEqual(this.props.Schema, nextProps.Schema)) {
this.setState({ display_name: nextProps.Schema.display_name, ...more})
}
}
答案 1 :(得分:0)
我看到您正在放display_name: this.props.Schema.display_name,
但随后您执行console.log(props)
。
我认为这里的问题是您需要:
this.state = {
display_name: props.Schema.display_name,
phone: props.Schema.phone,
email: props.Schema.email,
activated: props.Schema.activated,
groups: props.Schema.groups
}
答案 2 :(得分:-1)
您应该按照本例中的操作
render(){
const schema = this.props.Schema
return
(
<div>
<input
defaultValue={schema.display_name}
/>
</div>
)