[英]Cannot access props.navigation.state variables
I got undefined errors when I try to saving props.navigation.state variables into state and using them on components当我尝试将 props.navigation.state 变量保存到 state 并在组件上使用它们时出现未定义的错误
componentDidMount = () => {
this.setState({
services: this.props.navigation.state.params.data.vendor_types_and_services,
loading: false
})
}
then when I display the data it crash with error然后当我显示数据时它会因错误而崩溃
{!loading && <Text>{services.length}</Text>}
undefined is not an object (evaluating 'services.length')
undefined 不是 object(评估“services.length”)
When using the regular expression this.props.navigation.state.params.data.vendor_types_and_services
it works just fine, I am not sure where is the problem, this is a different route on appNavigator, what's the alternative to componentWillReceiveProps
or componentWillMount
?当使用正则表达式
this.props.navigation.state.params.data.vendor_types_and_services
时它工作得很好,我不确定问题出在哪里,这是 appNavigator 上的不同路线, componentWillReceiveProps
或componentWillMount
的替代方案是什么?
Please help!请帮忙!
Replace代替
{!loading && <Text>{services.length}</Text>}
With和
{!loading && this.state.services !== null && <Text>{this.state.services.length}</Text>}
And make sure you have defined this state variable into constructor like this:并确保您已将这个 state 变量定义到构造函数中,如下所示:
constructor(props) {
super(props);
this.state = {
services: null,
loading: true
};
}
try destructuring and debug with a console.log()
尝试使用
console.log()
进行解构和调试
const { params } = props.navigation.state;
can you show how you receive these props from another component?你能展示你如何从另一个组件接收这些道具吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.