Javascript 反应-检查是否存在道具
我在互联网上搜索这个问题的答案,但没有找到。因此,我将我的问题张贴在这里 我有一个父组件(App)和一个子组件(child)。 应用程序组件的状态中包含一些数据,如下所示:Javascript 反应-检查是否存在道具,javascript,reactjs,Javascript,Reactjs,我在互联网上搜索这个问题的答案,但没有找到。因此,我将我的问题张贴在这里 我有一个父组件(App)和一个子组件(child)。 应用程序组件的状态中包含一些数据,如下所示: class App extends Component { constructor() { super() this.state = { currentOrganization: { name: 'name',
class App extends Component {
constructor() {
super()
this.state = {
currentOrganization: {
name: 'name',
email: 'email'
}
}
render() {
return (
<Child data={this.state.currentOrganization} />
)
}
}
}
类应用程序扩展组件{
构造函数(){
超级()
此.state={
当前组织:{
姓名:'姓名',
电子邮件:“电子邮件”
}
}
render(){
返回(
)
}
}
}
在我的子组件中,我有一个表单:
class Child extends Component {
constructor() {
super()
this.state = {
formData: {
name: '',
email: '',
}
}
}
render() {
return (
<Form ... />
)
}
}
类子级扩展组件{
构造函数(){
超级()
此.state={
表格数据:{
名称:“”,
电子邮件:“”,
}
}
}
render(){
返回(
)
}
}
根据React文档,表单通常应该具有包含与表单的每个元素对应的属性的状态。my Child组件中的表单必须将currentOrganization(如应用程序组件中所示)的数据预填充到自身中
为了实现这一点,我必须将子对象的状态设置为它从父对象收到的道具
检查我的子组件是否收到了更新其自身状态所需的道具的最佳方法是什么?您可以为组件分配默认道具
class Child extends Component {
constructor(props) {
super(props);
this.state = {
formData: {
name: props.name,
email: props.email,
}
}
}
render() {
return (
<Form ... />
)
}
}
Child.defaultProps = {
name: '',
email: '',
};
类子级扩展组件{
建造师(道具){
超级(道具);
此.state={
表格数据:{
名称:props.name,
电子邮件:props.email,
}
}
}
render(){
返回(
)
}
}
Child.defaultProps={
名称:“”,
电子邮件:“”,
};
附言。
props
是JS对象,所以您可以像这样检查属性
“prop_name”在this.props//true | false
“React的团队没有添加像componentDidReceiveProps()这样的生命周期函数的原因是什么?”->componentWillReceiveProps()不适合您吗?React have组件将接收道具
有什么用?我的意思是,你是传递整个状态的人,而不是组件实际需要的-所以你需要检查构造中的道具,didMount,willReceiveProps,等等。我不太明白这个问题。这只是一个猜测,但因为有一个生命周期事件叫做componentWillReceiveProps
,你需要在那里设置你的状态,因为你的道具可能会导致重新渲染,如果你在componentWillReceiveProps之后设置你的状态,它将重新渲染again@Matt在荷兰不行这种情况。我需要检查以确保我的子组件确实收到了道具。我不需要知道这些道具是否会改变,只要知道它们是否存在就行了。如果我对该方法的理解是正确的,那么该方法“在安装的组件接收到新的道具之前被调用”。当它在安装时接收到初始道具时也是这样吗?尽管如此,下面的答案似乎已经足够了。+1用于在构造函数中使用props.xxx
,而不是this.props
,以及使用空字符串作为输入值而不是null。也可以这样写:const{name='',email='}=props
,然后this.state.formData({name,email})
在构造函数中。this.state.formData()
?抱歉,编写后一部分时太忙了。应该是this.state={formData:{name,email}}
@Rafael Hovsepyan cool,这正是我想要的。谢谢