我有这个饮食屏幕,我想在其中输出饮食名称和该饮食的禁用成分。饮食名称作为route.params传递到饮食屏幕。
export default function DietScreen({ route }) {
const { dietName } = route.params;
return (
<View>
<Text>Diet Screen</Text>
<Text>{JSON.stringify(dietName)}</Text>
<Ingredients dietName={JSON.stringify(dietName)} />
</View>
);
}它正确地输出了饮食名称,但是当我想在配料组件中打开firestore中的配料时,我得到了一个错误:"undefined is not an object(evaluating 'doc.data().forbidden_ingredients')"
class Ingredients extends React.Component {
constructor(props) {
super(props);
this.state = { ingredients: [] };
}
componentDidMount() {
try {
firestore()
.collection('Diets')
.doc(this.props.dietName)
.onSnapshot(doc =>
this.setState({
ingredients: doc.data().forbidden_ingredients,
})
);
} catch (e) {
console.log(e);
}
}
renderIngredients = () => {
return this.state.ingredients.map(ingredient => (
<Text key={ingredient}>{ingredient}</Text>
));
};
render() {
return <View>{this.renderIngredients()}</View>;
}
}正如您所看到的,我使用饮食名称作为id。当I console.log this.props.dietName时,我会得到正确的所需名称记录。如果我直接使用饮食名称,比如.doc("vegetarian"),我会得到正确的配料列表。但是由于某些原因,当I this.props.dietName在firestore请求中不能作为id工作时。
发布于 2020-09-30 20:23:56
我认为应该从DietScreen函数中删除JSON.stringify。而不是:
<Ingredients dietName={JSON.stringify(dietName)} />我认为应该是:
<Ingredients dietName={dietName} />不幸的是,我在reactjs中没有游乐场,但是如果我理解正确的话,dietName是一个字符串,所以在JS中,当你在字符串上使用JSON.stringify时,会得到带引号的字符串。
我们可以这样测试:
const params = {dietName: "one"}
const {dietName} = params;
const dietNameParam = JSON.stringify(dietName);
console.log(`dietNameParam is ${dietNameParam} and it's lenght is ${dietNameParam.length}`);
console.log(`while dietName is ${dietName} and it's lenght is ${dietName.length}`);如果你在某个地方运行它,比如here (只需将代码粘贴到演示窗口并点击run即可)。您将看到由JSON.stringify生成的字符串更长。
https://stackoverflow.com/questions/64124810
复制相似问题