反应上下文映射

React Context Mapping

我创建了一个全局上下文 api 以从我的 firebase 中提取所有数据,然后通过 React Provider 将其发送。但我似乎无法通过我收到的对象数组进行映射。

const Schedule = () => {
  const config = useContext(ConfigContext);
  return (
    <>
      <div id="ScheduleContainer" className="row">
        <div className="col-sm-4">
          <img
            src={clock}
            alt="clock"
            title="clock|Icon made by flaticon author dmitri13"
          ></img>
        </div>
        {console.log(config.scheduleMap)}
        <div className="col-sm-8">
          {config.scheduleMap.map((data) => (
            <h1>{data.Event}</h1>
          ))}
        </div>
      </div>
    </>
  );
};

我在控制台记录它的地方,我可以看到数据。显示如下:

但是当我尝试映射它时出现以下错误,TypeError: Cannot read property 'map' of undefined

Reference

当我们得到这样的错误时,我们可能正在以异步方式获取值。我们应该为我们的变量提供一个初始值或有条件地渲染它或两者兼而有之。

以下代码片段可能会解决您的问题。

{config.scheduleMap !== undefined ? 
    config.scheduleMap.map(data=>(
       <h1>{data.Event}</h1>))
     :
    ''
}