【发布时间】:2016-05-19 08:39:55
【问题描述】:
我正在传递一个流星集合作为我的一个组件中的道具,并试图弄清楚我什么时候真正收到道具?
我尝试访问(例如this.props.userData)getInitialState 中的道具说未定义,然后我尝试在 componentDidMount 中访问它说未定义,但在渲染方法中它工作正常。
render 之前或之后的哪个方法可以告诉我我可以访问道具?我想用 props 的值初始化 state。
例如,在下面的代码中,我收到一条错误消息,指出 userData 未定义。
getInitialState(){
return{
firstName : this.props.userData.firstName
}
}
编辑 所以我正在做这样的事情,我使用道具只是为了初始化状态变量。
export default React.createClass({
getInitialState(){
return {
email : this.props.user.email
}
},
onFormSubmit(event){
event.preventDefault();
},
onTextFieldChange(event){
switch (event.target.name) {
case "email":
this.setState({
email:event.target.value
});
break;
}
},
render() {
console.log(this.props.user.email);
return (
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title text-center"><strong>Sign in with Existing Account</strong></h3>
</div>
<form className="form-horizontal" id="frmSignIn" role="form" onSubmit={this.onFormSubmit}>
<div className="modal-body">
<div className="form-group">
<label className="col-xs-4 control-label">Email</label>
<div className="col-xs-8">
<input type="email" id="email" name="email" className="form-control"
value={this.state.email}
onChange={this.onTextFieldChange}
placeholder="example@domain.com"
required/>
</div>
</div>
<div className="form-group">
<label className="col-xs-4 control-label">Password</label>
<div className="col-xs-8">
<input type="password" id="password" name="password" className="form-control"
placeholder="Password"
required/>
<label id="signin-error" className="error"> </label>
</div>
</div>
</div>
<div className="panel-footer">
<label className="col-xs-4 control-label"></label>
<div className="col-xs-8">
<input type="submit" className="btn btn-primary pull-right" value="SignIn"/>
</div>
</div>
</form>
</div>
);
}
});
【问题讨论】:
-
你怎么称呼它?注意
getInitialState中的 props 是反模式 facebook.github.io/react/tips/… -
@JuanMendes 感谢您的评论,您能看到编辑吗?我正在做 fb 所说的,但我在输入字段中什么也没得到,尽管控制台日志显示值 correclty
-
你仍然没有解释它是如何被调用的,那是设置道具的地方,你可能没有设置默认道具。如果您将值从道具复制到状态,则不应使用
this.props.user.email,而应使用this.state.user.email -
在
getInitialState中尝试console.loggingthis.props和componentWillReceiveProps中的下一个道具。然后你会看到你的组件何时以及如何接收到提到的属性值
标签: javascript meteor reactjs react-native