当我试图将props.navigation.state变量保存到状态并在组件上使用它们时,我遇到了未定义的错误
componentDidMount = () => {
this.setState({
services: this.props.navigation.state.params.data.vendor_types_and_services,
loading: false
})
}
然后当我显示数据时,它崩溃了,出现错误
{!loading && <Text>{services.length}</Text>}
undefined不是对象(评估"services.length"(
当使用正则表达式this.props.navigation.state.params.data.vendor_types_and_services
时,它工作得很好,我不确定问题出在哪里,这是appNavigator上的不同路线,componentWillReceiveProps
或componentWillMount
的替代方案是什么?
请帮忙!
更换
{!loading && <Text>{services.length}</Text>}
带
{!loading && this.state.services !== null && <Text>{this.state.services.length}</Text>}
并确保您已经将这个状态变量定义到构造函数中,如下所示:
constructor(props) {
super(props);
this.state = {
services: null,
loading: true
};
}
尝试使用console.log()
进行析构和调试
const { params } = props.navigation.state;
你能展示一下你是如何从另一个组件接收这些道具的吗?