首页 > 解决方案 > 无法在 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 工作时。

标签: reactjsfirebasegoogle-cloud-firestorethisnative

解决方案


我认为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更长了。


推荐阅读