首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在firebase firestore请求中以id的身份访问this.props (react本机)

无法在firebase firestore请求中以id的身份访问this.props (react本机)
EN

Stack Overflow用户
提问于 2020-09-30 01:37:49
回答 1查看 55关注 0票数 0

我有这个饮食屏幕,我想在其中输出饮食名称和该饮食的禁用成分。饮食名称作为route.params传递到饮食屏幕。

代码语言:javascript
复制
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')"

代码语言:javascript
复制
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工作时。

EN

回答 1

Stack Overflow用户

发布于 2020-09-30 20:23:56

我认为应该从DietScreen函数中删除JSON.stringify。而不是:

代码语言:javascript
复制
<Ingredients dietName={JSON.stringify(dietName)}  />

我认为应该是:

代码语言:javascript
复制
<Ingredients dietName={dietName} />

不幸的是,我在reactjs中没有游乐场,但是如果我理解正确的话,dietName是一个字符串,所以在JS中,当你在字符串上使用JSON.stringify时,会得到带引号的字符串。

我们可以这样测试:

代码语言:javascript
复制
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生成的字符串更长。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64124810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档