将子道具传递给 Gatsby V2 中的子组件
Passing child props to child component in Gatsby V2
自升级到使用 Gatsby V2 以来,我一直在努力将 this.state
传递给子组件以用作 this.props
。
例如,我有一个容器,其中 data1
和 data2
添加到 this.state
作为
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>
);
}
}
和子组件
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<h1>{this.props.data1}</h1>
<p>{this.props.data2}</p>
);
}
}
最后,
将其带入页面
const Page = () => (
<Parent authUserID="01234" campaignID="56789">
<Child />
</Parent>
);
在 Gatsby V1 中这是有效的,但现在随着迁移我收到错误 Uncaught Error: Objects are not valid as a React child (found: object with keys {authUserID, campaignID, children}). If you meant to render a collection of children, use an array instead.
谁能告诉我为什么以及如何解决这个问题?
您在 Parent
组件中将整个道具对象用作子对象。确保从 props 中解构 children
对象,它将按预期工作。
const { children } = this.props;
自升级到使用 Gatsby V2 以来,我一直在努力将 this.state
传递给子组件以用作 this.props
。
例如,我有一个容器,其中 data1
和 data2
添加到 this.state
作为
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>
);
}
}
和子组件
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<h1>{this.props.data1}</h1>
<p>{this.props.data2}</p>
);
}
}
最后,
将其带入页面const Page = () => (
<Parent authUserID="01234" campaignID="56789">
<Child />
</Parent>
);
在 Gatsby V1 中这是有效的,但现在随着迁移我收到错误 Uncaught Error: Objects are not valid as a React child (found: object with keys {authUserID, campaignID, children}). If you meant to render a collection of children, use an array instead.
谁能告诉我为什么以及如何解决这个问题?
您在 Parent
组件中将整个道具对象用作子对象。确保从 props 中解构 children
对象,它将按预期工作。
const { children } = this.props;