收到的道具在本机导航中未定义

我正在尝试访问传递给本机组件的道具,但该组件似乎未收到道具。传递 props(PastHires.js) 的组件:


return (

  <ScrollView style={styles.container}>

    <Text style={styles.heading}>Past Hires</Text>

      {

        this.state.boards.filter(item => item.driverId === this.props.user.id && item.hireStatus === 'completed' ).map((item, i) => (

          <ListItem

            style={styles.listItem}

            key={i}

            title={item.pickupDatetime + '  ' + item.hireType.toUpperCase() + '  ' + item.pickupLocation.toUpperCase()}

            leftIcon={{name: 'book', type: 'font-awesome'}}

            onPress={() => {

              this.props.navigation.navigate('PastHireDetails', {

                hireId: 12,

              });

            }}

          />

        ))

      }

  </ScrollView>

);

}


接收道具的组件(PastHireDetails.js):


componentDidMount() {

const { navigation } = this.props;

// console.log(navigation.state)

const ref = Firebase.firestore().collection('hires').doc(JSON.parse(navigation.getParam('hireId')));

ref.get().then((doc) => {

  if (doc.exists) {

    this.setState({

      hire: doc.data(),

      key: doc.id,

      isLoading: false

    });

  } else {

    console.log("No such document!");

  }

});

}


这会引发语法错误:JSON Parse Error: Unexpected identifier "undefined" When I console log navigation.state 它返回该参数未定义


Object {

  "key": "PastHireDetails",

  "params": undefined,

  "routeName": "PastHireDetails",

}

我在这里做错了什么吗?任何修复?


阿晨1998
浏览 128回答 2
2回答

ABOUTYOU

如果你使用了 react-navigation,试试这个来访问导航参数&nbsp;componentDidMount() {&nbsp; &nbsp; const { navigation } = this.props;&nbsp; &nbsp; // console.log(navigation.state);&nbsp; &nbsp; const hireId = navigation.state.params.hireId;&nbsp; &nbsp; const ref = Firebase.firestore().collection('hires').doc(hireId);&nbsp; &nbsp; ref.get().then((doc) => {&nbsp; &nbsp; &nbsp; if (doc.exists) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hire: doc.data(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key: doc.id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isLoading: false&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; console.log("No such document!");&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp;&nbsp;}并参考这个类似的问题 https://stackoverflow.com/questions/58279318/navigation-getparam-in-not-an-object/58280498#58280498

一只名叫tom的猫

this.props.navigation.navigate('PastHireDetails', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hireId: 12,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })在上面的行中,您设置了一个名为hiringId 的导航参数,它是一个整数const { navigation } = this.propsnavigation.getParam('hireId')navigation.getParam('hireId') 将返回一个整数值但是在另一个脚本中,您可以通过以下方式将该整数转换为 JSON JSON.parse(navigation.getParam('hireId'))这会给你一个错误尝试删除 JSON.parse 因为它已经是您想要的整数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript