简体   繁体   English

尝试将 map 输出 state 并将其作为道具传递给组件时,“无法读取未定义的属性‘映射’”

[英]“Cannot read property 'map' of undefined” when trying to map out state and pass it as props into component

So I have my main functional component IndexHeaderHome and I am trying to set the state allDeals, and then pass that state as props into the component Tabs.所以我有我的主要功能组件IndexHeaderHome,我正在尝试设置state allDeals,然后将state作为道具传递到组件选项卡中。 For some reason tho I am getting this map undefined error and after a bit of tinkering I am unable to figure out a solution, I am hoping someone can point out where I am going wrong.出于某种原因,我收到了这个 map 未定义错误,经过一番修补后,我无法找到解决方案,我希望有人能指出我哪里出错了。 Thanks so much =]非常感谢=]



function IndexHeaderHome() {
  const pageHeader = React.useRef();
  const [allDeals, setAllDeals] = React.useState();

  React.useEffect(() => {
    if (window.innerWidth > 991) {
      const updateScroll = () => {
        let windowScrollTop = window.pageYOffset / 3;
        pageHeader.current.style.transform =
          "translate3d(0," + windowScrollTop + "px,0)";
      };
      window.addEventListener("scroll", updateScroll);
      return function cleanup() {
        window.removeEventListener("scroll", updateScroll);
      };
    }
    // no deps array makes it so the effect runs on every render
    // an empty one will run only on mount
  }, []);

  // Ive never used firebase, but I'm guessing you want
  // to initialize firestore only once and put it in a ref

  useEffect(() => {
    const getStuff = async () => {
      const db = firebase.firestore();
      let citiesRef = db.collection("Live_Deals");
      let query = citiesRef
        .where("liveDiscountActive", "==", true)
        .get()
        .then((snapshot) => {
          if (snapshot.empty) {
            console.log("No matching documents.");
            return;
          }

          snapshot.forEach((doc) => {
            console.log(doc.id, "=>", doc.data());
            let data = doc.data();
            let deals = JSON.parse(data);

            setAllDeals(deals);
          });
        })
        .catch((err) => {
          console.log("Error getting documents", err);
        });
    };
  }, []);

  const [iconPills, setIconPills] = React.useState("1");
  const [pills, setPills] = React.useState("1");

  return (
    <>
      <div className="page-header clear-filter" filter-color="blue">
        <div
          className="page-header-image"
          style={{
            backgroundImage: "url(" + require("assets/img/header.jpg") + ")",
          }}
          ref={pageHeader}
        ></div>
        <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />{" "}
        <br /> <br /> <br />
        <Container>
          <div className="content-center brand">
            <h1 className="h1-seo">Get updates on the latest deals!</h1>
            <h3>Save money everyday with our live deal updates!</h3>
          </div>
        </Container>
        <Container>
          <FilterNow />
          {allDeals.map(() => (
            <Tabs
              DealName={discountName}
              DealDisc={discountDesc}
              DealEnd={discountEdate}
              DealCat={discountDesc}
              DealDisp={discountDisp}
            />
          ))}
        </Container>
      </div>
    </>
  );
}
export default IndexHeaderHome;

the error is on this line here错误在这里


          {allDeals.map(() => (

You set allDeals to null by default by using useState() just null check it and you will be fine;默认情况下,您使用useState()allDeals设置为 null ,只需 null 检查它就可以了;

{allDeals ? allDeals.map(() => (
            <Tabs
              DealName={discountName}
              DealDisc={discountDesc}
              DealEnd={discountEdate}
              DealCat={discountDesc}
              DealDisp={discountDisp}
            />
          )):null}

PS: Ideally you might want to render spinner or some kinda loading component while it is loaded asyncronously PS:理想情况下,您可能希望在异步加载时渲染微调器或某种加载组件

You will need to add a null checking or an initial state on that.您需要在其上添加 null 检查或初始 state。

Example of null checking null 检查示例

{allDeals && allDeals.map(() => ()}

With initial State带初始 State

const [allDeals, setAllDeals] = React.useState([]);

{allDeals.length > 0 && allDeals.map(() => ()}

暂无
暂无

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

相关问题 尝试设置 state 道具并将其传递到组件时“无法读取未定义的属性‘状态’” - “Cannot read property 'state' of undefined” when trying to set and pass state props into a component TypeError: Cannot read property 'map' of undefined 当我尝试 map 通过从父组件传递到子组件的道具时显示 - TypeError: Cannot read property 'map' of undefined is showing when I'm trying to map over the props passed from parent component to child component 尝试 map 我的道具时,我收到无法读取未定义错误的“练习”属性 - I'm getting a Cannot read property of 'exercises' of undefined error when trying to map my props 销毁道具时无法读取未定义的属性“地图” - Cannot read property 'map' of undefined when destructing props TypeError:尝试读取通过props传递的数组时,无法读取未定义的属性“ map” - TypeError: Cannot read property 'map' of undefined, while trying to .map() an array passed through props 状态更新后“无法读取未定义的属性&#39;map&#39;” - “cannot read property 'map' of undefined” when state is updated ReactJS 传递给变量时“无法读取未定义的属性‘映射’” - “Cannot read property 'map' of undefined” when it is pass to a variable React 无法读取组件上未定义的属性“映射” - React cannot read property 'map' of undefined on component React props未定义-无法读取未定义的属性“地图” - React props is undefined - Cannot read property 'map' of undefined 无法读取 React-redux 上未定义错误的属性“地图”,尽管使用道具而不是 state - cannot read property 'map' of undefined error on React-redux, despite using props instead of state
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM