reactjs - 无法在 firebase firestore 请求中将 this.props 作为 id 访问(反应原生)
问题描述
我有这个饮食屏幕,我想在其中输出饮食名称和该饮食的禁用成分。饮食名称作为 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。当我 console.log 时,this.props.dietName
我会记录正确的所需名称。如果我直接使用饮食名称,就像.doc("vegetarian")
我得到正确的成分表一样。但是由于某种原因,当我this.props.dietName
在 Firestore 请求中不作为 id 工作时。
解决方案
我认为JSON.stringify
应该从DietScreen
功能中删除。代替:
<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}`);
如果你在某个地方运行它,比如这里(只需将代码粘贴到演示窗口并点击运行)。你会看到生成的字符串JSON.stringify
更长了。
推荐阅读
- python - 根据列表中值的顺序对键进行排序
- c - 三种颜色三角形
- sql - SQL 按日期聚合
- c# - 如何使用 Ajax 和 C# 从数据库中填充 FullCalendar
- python - PyOpenGL 片段着色器纹理采样
- python - 如何在不使用模块的情况下使用每行的字数在python中拆分文本文件
- ios - 如何使用委托方法从捕获会话中提取视频?
- python - Itertools 循环方法——为什么是“while”循环?
- python - 没有出现在 Tensorflow-PyCharm IDE 中的可视化
- excel - VBA 或 Excel 函数计算逗号分隔字符串中的非零