【问题标题】:React: Conditional Render - "Cannot read property '0' of null" [duplicate]反应:条件渲染-“无法读取空属性'0'” [重复]
【发布时间】:2021-02-24 17:16:13
【问题描述】:

突出我的问题。我正在尝试向图像道具添加条件渲染。我从 API 中提取的一些“故事”没有图像,所以我需要考虑这一点,所以我没有收到“TypeError:无法读取 null 的属性 '0'”错误,但这仍然不起作用我添加了三元运算符。

<Story
  key={idx}
  title={story.title}
  abstract={story.abstract}
  img={story.multimedia[0].url ? story.multimedia[0].url : null} // why doesn't this work?
  alt={story.multimedia[0].caption ? story.multimedia[0].caption : null} // why doesn't this work?
  link={story.url}
/>;

我可以向“占位符”图片网址添加后备链接吗?

  img={story.multimedia[0].url ? story.multimedia[0].url : "https://www.example.com/example.png"}

这里是完整的组件

export default function News() {
  const [error, setError] = useState(null);
  const [stories, setStory] = useState(null);

  useEffect(() => {
    const getCurrentPage = () => {
      const url = new URL(window.location.href);
      const page = url.pathname.split("/").pop();
      return page ? page : "home";
    };
    const section = getCurrentPage();
    fetch(
      `https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=4fzCTy6buRI5xtOkZzqo4FfEkzUVAJdr`
    )
      .then((res) => res.json())
      .then((data) => {
        setTimeout(() => setStory(data), 1500);
        console.log("Success ", data);
      })
      .catch((error) => {
        console.log("Error", error);
        setError(error);
      });
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!stories) {
    return <LoadingBar type={"cylon"} color={"#193152"} />;
  } else {
    return (
      <>
        <ul className="stories">
          {stories.results.map((story, idx) => {
            return (
              <Story
                key={idx}
                title={story.title}
                abstract={story.abstract}
                img={story.multimedia[0].url ? story.multimedia[0].url : null} // why doesn't this work
                alt={ story.multimedia[0].caption ? story.multimedia[0].caption : null } // why doesn't this work?
                link={story.url}
              />
            );
          })}
        </ul>
        <Spacer height={100} />
      </>
    );
  }
}

【问题讨论】:

  • 问题是story.multimedia 为空。在三元条件下会引发错误,因此您需要使用story.multimedia ? story.multimedia[0].url : ... 来检查条件中的空值,或者,如果您的目标是现代浏览器,则使用可选链接; story.multimedia?.[0]?.url ? story.multimedia[0].url : ...
  • 我不知道这是否有帮助,但如果你尝试这样的事情:img={!story.multimedia[0].url ? null : story.multimedia[0].url}
  • 如果你使用optional chaining,你可能甚至不需要三元img={story?.multimedia?.[0]?.url},因为这是JSX,babel 无论如何都会编译它,所以很可能不用担心浏览器支持.

标签: javascript reactjs


【解决方案1】:

Cannot read property '0' of null" 暗示 story.multimedianull,这没有被检查。

您可能应该像这样扩展您的检查:

story && story.multimedia && story.multimedia[0] && story.multimedia[0].url ? story.multimedia[0].url : null

story && story.multimedia && story.multimedia[0] && story.multimedia[0].caption ? story.multimedia[0].caption : null

或者如果你想使用可选链(如果你的环境支持的话):

story?.multimedia?.[0]?.url || null

story?.multimedia?.[0]?.caption || null

【讨论】:

  • 如果您真的想要 null 而不是(可能)未定义,请使用 nullish coalescing operator ?? 而不是 OR。
  • 这是一个很好的观点@HereticMonkey。 || 检查虚假值。可能你仍然想在这里使用||,因为你不太可能想要url 作为0"",例如
  • 第一个例子完美运行!
【解决方案2】:

尝试检查类型:

 {  typeof story.multipedia[0].url === "undefined"
     ? img_default
     : story.multimedia[0].url
 }

【讨论】:

  • 这仍然会抛出同样的错误,假设story.multipedia[0] == null
  • 假设story.multipedia[0] === null是可能的,你也可以用if (story.multipedia[0])检查它
【解决方案3】:

看起来story.multimedia 可以是null。如果您的环境(例如,通过 babel)支持此功能,请使用 story.multimedia?.[0],或者使用老派并使用 story.multimedia &amp;&amp; story.multimedia[0]

【讨论】:

  • 数组可选链的语法是?.[0],(带点)
  • 而且它在副本中被覆盖了......
猜你喜欢
  • 2017-05-31
  • 2021-01-12
  • 2020-12-02
  • 2016-01-31
  • 1970-01-01
  • 2022-01-17
  • 2019-03-25
  • 2021-05-01
相关资源
最近更新 更多