开发者问题收集

TypeError:未定义不是一个对象(评估'events [genre]')

2020-05-31
720

我正在尝试创建一个自定义数组,但 for 循环无法评估 events[genre][0].name,因为由于 firebase 的异步特性,事件尚未设置。有没有办法只在数据设置后执行 for 循环,或者有什么解决方法?

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];  

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });
  });

  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);
2个回答

首先,您不能在没有任何依赖的情况下执行 useEffect,特别是因为它在其中设置了一个状态,否则您的应用程序将陷入无限循环

其次,您可以在实际使用解析数据之前处于加载状态

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const testEvents = ["arts", "leisure", "sports"];  

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
        setIsLoading(false);
      });
  }, []); // executed on initial render

  if(isLoading) {
     return <div>Loading...</div>
  }
  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);
Shubham Khatri
2020-05-31

您需要等待 事件 完成,您可以通过以下方式实现:

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];  

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });

    if (events.length) {
      // use you loop here
    }
  }, events.length);

  ...
}
zronn
2020-05-31