这是我的父代码:
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
tags: [],
};
}
componentDidMount() {
this.getTags();
}
getTags() {
//method gets tags from the backend
}
render() {
return <Child tags={this.state.tags} />;
}
}
这基本上是我的子组件:
export default class Child extends Component {
constructor(props) {
super(props);
this.state = {
tags: props.tags,
};
}
componentWillReceiveProps(nextProps) {
this.setState({
tags: nextProps.tags,
});
}
}
但是当我在组件中的某处控制台日志标签时Child
,它是未定义的。也许它是未定义的,因为子组件在父组件调用方法之前被渲染getTags
?或者这段代码还有其他问题吗?以及如何避免子组件中未定义标签的问题?
干杯