繁体   English   中英

无法访问 props.navigation.state 变量

[英]Cannot access props.navigation.state variables

当我尝试将 props.navigation.state 变量保存到 state 并在组件上使用它们时出现未定义的错误

  componentDidMount = () => {
    this.setState({
      services: this.props.navigation.state.params.data.vendor_types_and_services,
      loading: false
    })
  }

然后当我显示数据时它会因错误而崩溃

  {!loading &&  <Text>{services.length}</Text>}

undefined 不是 object(评估“services.length”)

当使用正则表达式this.props.navigation.state.params.data.vendor_types_and_services时它工作得很好,我不确定问题出在哪里,这是 appNavigator 上的不同路线, componentWillReceivePropscomponentWillMount的替代方案是什么?

请帮忙!

代替

{!loading &&  <Text>{services.length}</Text>}

{!loading && this.state.services !== null &&  <Text>{this.state.services.length}</Text>}

并确保您已将这个 state 变量定义到构造函数中,如下所示:

constructor(props) {
  super(props);
  this.state = {
    services: null,
    loading: true
  };
}

尝试使用console.log()进行解构和调试

const { params } = props.navigation.state;

你能展示你如何从另一个组件接收这些道具吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM