React 道具值未定义
React props value is undefined
这是我的 parent 代码:
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} />;
}
}
这基本上是我的 child 组件:
export default class Child extends Component {
constructor(props) {
super(props);
this.state = {
tags: props.tags,
};
}
componentWillReceiveProps(nextProps) {
this.setState({
tags: nextProps.tags,
});
}
}
但是当我在 Child
组件的某处控制日志标签时,它是未定义的。也许它是未定义的,因为 child 组件在 parent 组件调用方法 getTags
之前渲染?或者这段代码还有其他问题吗?以及如何避免 child 组件中标签未定义的问题?
干杯
为避免您的问题,在 this.state.tags
具有任何有用的值之前,您不应渲染 Child
组件。
您可以按照以下方法进行操作,并显示 "Loading..." 文本,这样用户就不用担心页面损坏了。
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} />
);
}
}
您的 child 组件肯定会使用空 'tags' 数组作为道具进行渲染。然后,当 getTags() returns 数据时,新填充的标签数组将作为 prop 传递给 child,强制 child 获取 re-rendered with the new数据.
虽然它应该是空数组,而不是 "undefined"。您可以检查您的 getTags() 方法和您正在调用的 API 以确保您没有从那里获得 "undefined"。
componentWillReceiveProps 是遗留的,不应使用。有关详细信息,请参阅 React 文档中的以下 link:https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
该文档将引导您了解如果您需要因更改道具而产生副作用时该怎么做。
现在唯一的事情就是 componentWillReceiveProps 是给 props 设置本地状态,这完全是多余的。还有什么你需要在那里做的吗?
这是我的 parent 代码:
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} />;
}
}
这基本上是我的 child 组件:
export default class Child extends Component {
constructor(props) {
super(props);
this.state = {
tags: props.tags,
};
}
componentWillReceiveProps(nextProps) {
this.setState({
tags: nextProps.tags,
});
}
}
但是当我在 Child
组件的某处控制日志标签时,它是未定义的。也许它是未定义的,因为 child 组件在 parent 组件调用方法 getTags
之前渲染?或者这段代码还有其他问题吗?以及如何避免 child 组件中标签未定义的问题?
干杯
为避免您的问题,在 this.state.tags
具有任何有用的值之前,您不应渲染 Child
组件。
您可以按照以下方法进行操作,并显示 "Loading..." 文本,这样用户就不用担心页面损坏了。
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} />
);
}
}
您的 child 组件肯定会使用空 'tags' 数组作为道具进行渲染。然后,当 getTags() returns 数据时,新填充的标签数组将作为 prop 传递给 child,强制 child 获取 re-rendered with the new数据.
虽然它应该是空数组,而不是 "undefined"。您可以检查您的 getTags() 方法和您正在调用的 API 以确保您没有从那里获得 "undefined"。
componentWillReceiveProps 是遗留的,不应使用。有关详细信息,请参阅 React 文档中的以下 link:https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
该文档将引导您了解如果您需要因更改道具而产生副作用时该怎么做。
现在唯一的事情就是 componentWillReceiveProps 是给 props 设置本地状态,这完全是多余的。还有什么你需要在那里做的吗?