我正在用 react.js 编写我的应用程序并尝试从组件(P)的子组件(C1)获取数据,它是一个对象数组,然后再次将数据传递给另一个子组件(C2)。但是,当我在(C2)中控制台记录到达的数据时,奇怪的是它显示数据在那里,但是当我控制台记录它的'属性时,它说它无法读取未定义的属性。代码如下:
class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
photos: []
}
}
myCallback = dataFromChild1 => {
this.setState({
photos: dataFromChild1
})
render(){
const { photos } = this.state;
return (
<main>
<Child1 callbackFromParent={this.myCallback} />
<Child2 photos={photos} />
</main>
)
}
class Child1 extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const photos = [{width: '100px'}, {width: '150px'}];
this.props.callbackFromParent(photos);
}
render() {
return (
<main>
...
</main>
)
}
}
function Child2(props) {
const photos = props.photos;
console.log(photos) // > [{..},{..}]
console.log(photos[0].width) // > cannot read property 'width' of undefined
return (
<main>
...
</main>
)
}
这个小提琴就是你正在寻找的。
这是代码:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
photos: []
}
}
myCallback = dataFromChild1 =>{
this.setState({
photos: dataFromChild1
});
};
render() {
const { photos } = this.state;
return (
<main>
<Child1 callbackFromParent={this.myCallback}/>
<Child2 photos={photos} />
</main>
);
}
}
class Child1 extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
const photos = [{width: '100px'}, {width: '150px'}];
this.props.callbackFromParent(photos);
}
render() {
return (
<main>
...
</main>
)
}
}
function Child2(props) {
const photos = props.photos;
console.log(photos) // > [{..},{..}]
console.log(photos[0] ? photos[0].width : undefined) // > cannot read property 'width' of undefined
return (
<main>
...
</main>
)
}
ReactDOM.render(
<ParentComponent name="World" />,
document.getElementById('container')
);
setState 是异步的,所以在第一次渲染中你的数据数组是空的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句