Javascript 在盖茨比V2中将子道具传递给子组件
自从升级到使用Gatsby V2以来,我一直在努力将Javascript 在盖茨比V2中将子道具传递给子组件,javascript,reactjs,gatsby,Javascript,Reactjs,Gatsby,自从升级到使用Gatsby V2以来,我一直在努力将this.state传递给要用作this.props的子组件 例如,我有一个容器,它将data1和data2添加到this.stateas class Parent extends React.Component { constructor(props) { super(props); this.state = { data1: '', data2: '' }; } componentDid
this.state
传递给要用作this.props
的子组件
例如,我有一个容器,它将data1
和data2
添加到this.state
as
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
data1: '',
data2: ''
};
}
componentDidMount() {
// Loading database
.then(doc =>
this.setState({
data1: doc.data().data1,
data2: doc.data().data2
})
);
}
render() {
const children = this.props;
const stateAsProps = React.Children.map(children, child =>
React.cloneElement(child, {
data1: this.state.data1,
data2: this.state.data2
})
);
return (
<div>{stateAsProps}</div>
);
}
}
类父级扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据1:“”,
数据2:“”
};
}
componentDidMount(){
//加载数据库
。然后(doc=>
这是我的国家({
data1:doc.data().data1,
data2:doc.data().data2
})
);
}
render(){
const children=this.props;
const stateAsProps=React.Children.map(Children,child=>
反应。克隆元素(儿童{
data1:this.state.data1,
data2:this.state.data2
})
);
返回(
{stateAsProps}
);
}
}
和一个子组件
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<h1>{this.props.data1}</h1>
<p>{this.props.data2}</p>
);
}
}
类子级扩展组件{
建造师(道具){
超级(道具);
this.state={};
}
render(){
返回(
{this.props.data1}
{this.props.data2}
);
}
}
最后,这是由
const Page = () => (
<Parent authUserID="01234" campaignID="56789">
<Child />
</Parent>
);
const Page=()=>(
);
在gatsbyv1中,这是可行的,但是现在在迁移过程中,我收到一个错误Uncaught错误:对象作为React子对象无效(找到:具有键{authUserID,ActivityId,children}的对象)。如果要呈现子对象集合,请改用数组。
有人能告诉我们为什么以及如何纠正这个问题吗 您正在将整个道具对象用作父组件中的子对象。确保从道具中解构出
子对象
对象,它将按预期工作
const { children } = this.props;
尝试编写
const{children}=this.props
而不是const children=this.props我觉得自己很笨。是的,谢谢你。如果你加上这个作为回答,我一定会接受的。