javascript - React 道具值未定义
问题描述
这是我的父代码:
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
?或者这段代码还有其他问题吗?以及如何避免子组件中未定义标签的问题?
干杯
解决方案
为避免您的问题,在具有任何有用值之前,您不应该渲染您的Child
组件。this.state.tags
这是您如何做到这一点并显示“正在加载...”文本,因此用户不必担心页面损坏。
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
tags: [],
};
}
componentDidMount() {
this.getTags();
}
getTags() {
//method gets tags from the backend
}
render() {
return this.state.tags.length ? (
'Loading...'
) : (
<Child tags={this.state.tags} />
);
}
}
推荐阅读
- picocli - PicoCLI :我如何使用@ArgGroup 作为方法?
- mybatis - 尝试从 ibatis 版本 2 升级到 mybatis 3.3,卡在下面的代码片段中
- node.js - Firebase onCreate 方法未触发
- reactjs - 如何在反应表上打开表行?
- extjs - ExtJS 在 Safari 14 上冻结
- sql - 创建不重复同一列的 SQL 表
- vue.js - Vue:测试 utils vue 组合 - root.$route
- c - C - 我应该使用引号还是方括号将标题包含在单独的目录中
- docker - Docker 日志 - 将时间从主机同步到容器
- php - 有没有办法让 PHP 在表格中向下获取第二行的值?