我正在尝试访问传递给react native组件的道具,但似乎该组件未接收到道具。传递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解析错误:意外的标识符“未定义”当我控制台日志navigation.state时,它返回未定义的参数
Object {
"key": "PastHireDetails",
"params": undefined,
"routeName": "PastHireDetails",
}
我在这里做错什么了吗?有任何修复程序吗?
如果使用了react-navigation,请尝试此操作以访问导航参数
componentDidMount() {
const { navigation } = this.props;
// console.log(navigation.state);
const hireId = navigation.state.params.hireId;
const ref = Firebase.firestore().collection('hires').doc(hireId);
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
hire: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
并参考类似的问题https://stackoverflow.com/questions/58279318/navigation-getparam-in-not-an-object/58280498#58280498
this.props.navigation.navigate('PastHireDetails', {
hireId: 12,
})
在上面的行中,您设置了一个名为hiredId的导航参数,它是一个整数
const { navigation } = this.props
navigation.getParam('hireId')
navigation.getParam('hireId')将返回一个整数值
但是在另一个脚本中,您可以通过以下方式将该整数转换为JSON:JSON.parse(navigation.getParam('hireId'))
这将为您抛出错误
尝试删除JSON.parse,因为它已经是您想要的整数了