简体   繁体   English

如何渲染依赖 firebase 异步函数的组件?

[英]How to render components that rely on firebase async functions?

I'm unable to have my component render the value from events[0].我无法让我的组件呈现来自事件 [0] 的值。 I've tried putting the data array in the.then block but the scoping gets screwed up.我试过将数据数组放在 then 块中,但范围界定被搞砸了。 Since firebase requests are async, how can I make the whole component render only when I receive my data from firebase?由于 firebase 请求是异步的,我怎样才能让整个组件仅在我从 firebase 收到数据时才呈现?

Finalized.js Finalized.js

const Finalized = () => {
  let events = [];
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      events.push(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,  // {events[0]} has no value returned
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};

You can use a state called events instead of the variable.您可以使用state调用events而不是变量。

Here is how to do it...这是如何做到的...

const [events, setEvents] = useState([]);

const Finalized = () => {
  firebase
    .database()
    .ref("events/arts/" + 2 + "/name")
    .once("value")
    .then((snapshot) => {
      setEvents(snapshot.val());
    });
  let data = [{
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0]}</Text>,
    }];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM