Javascript 反应道具值未定义
这是我的父代码:Javascript 反应道具值未定义,javascript,reactjs,react-props,componentwillreceiveprops,Javascript,Reactjs,React Props,Componentwillreceiveprops,这是我的父代码: class Parent extends Component { constructor(props) { super(props); this.state = { tags: [], }; } componentDidMount() { this.getTags(); } getTags() { //method gets tags
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} />;
}
}
但是当我在子组件中的某个地方控制台日志标记时,它是未定义的。可能它是未定义的,因为子组件在父组件调用方法getTags
之前被呈现?或者这个代码还有其他问题吗?如何避免子组件中未定义标记的问题
干杯为了避免您的问题,在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} />
);
}
}
类父级扩展组件{
建造师(道具){
超级(道具);
此.state={
标签:[],
};
}
componentDidMount(){
this.getTags();
}
getTags(){
//方法从后端获取标记
}
render(){
返回this.state.tags.length(
“正在加载…”
) : (
);
}
}
您的子组件肯定会以空的“标记”数组作为道具呈现。然后,当getTags()返回数据时,新填充的标记数组将作为道具传递给子对象,强制子对象使用新数据重新渲染
但它应该是空数组,而不是“未定义”。您可以检查getTags()方法和正在调用的API,以确保没有从中得到“未定义的”
componentWillReceiveProps是遗留的,不应使用。有关详细信息,请参见React文档中的以下链接:
该文档将指导您如何处理因更换道具而产生的副作用
现在唯一的事情是componentWillReceiveProps将本地状态设置为props,这是完全多余的。你在那里还需要做些什么吗 但是当我在子组件的某个地方控制台日志标记时。“某处”在哪里?您能在调用控制台.log的地方输入代码吗?
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} />
);
}
}