我正在尝试访问传递给React Native组件的道具,但似乎该组件未接收到道具。 传递props(PastHires.js)的组件:
let requiredListingDocs = [];
//with cursor limit can be removed if it was there to bring only some documents in memory
const cursor = ListingModel.find({})
.populate({
path: "listingLikes",
match: { userId: userId },
options: { limit: 10 }
})
.cursor();
//will contain listingLikes [] empty/or null for Listing docs that user didn't like
//looping on cursor which returns promise
for await (const doc of cursor) {
if (doc["listingLikes"] === null || doc["listingLikes"].length === 0) {
requiredListingDocs.push(doc);
}
}
console.info("LISTING DATA::", requiredListingDocs);
}
接收道具的组件(PastHireDetails.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>
);
}
这将引发语法错误:JSON解析错误:意外的标识符“未定义” 当我控制台日志navigation.state时,它返回未定义的参数
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!");
}
});
我在这里做错什么了吗?有修复程序吗?
答案 0 :(得分:0)
如果您使用了反应导航,请尝试此操作以访问导航参数
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
答案 1 :(得分:0)
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,因为它已经是您想要的整数