如何解决在 React 中使用 If 语句
我对使用 React 编码相当陌生。我正在尝试使用 if / else 语句,然后在内容正文中使用结果。此外,另一个重要信息是这与 Sanity CMS 相关联,因此我从数据库中提取内容。我想我遗漏了一些非常简单的东西,但从 React 的角度来看,我错误地使用了 if 语句。我已经阅读了文档,但需要一些新的视角。
我也遇到了一个错误: return null = 'return' 语句只能在函数体内使用。
import { SanityContent } from "../../components/sanityContent";
import { Post,getPosts } from "../../utils/getPosts";
import { useDomain } from "../../utils/domain";
const post = getPosts();
if (post.title = 'Cookie Policy'){
<div> post.legalDoc </div>
}
if (!post) {
return null;
}
function CookiePolicy() {
return (
<Layout>
<SanityContent content={post.legalDoc} />
有什么想法吗?
解决方法
是的,这很奇怪,但也很简单。
代码的解决方案:
import { SanityContent } from "../../components/sanityContent";
import { Post,getPosts } from "../../utils/getPosts";
import { useDomain } from "../../utils/domain";
function CookiePolicy() {
const test = () => {
const post = getPosts();
if (post.title === "Cookie Policy") {
console.log("YUP");
return <div>{post.legalDoc}</div>;
} else {
console.log("NOPE");
return null;
}
};
return <div>{test()}</div>;
}
我还制作了一个 codesandbox 来演示。
此外,如果您需要在组件中使用异步 if-check 函数,我在这里回答了一个类似的问题:objects are not valid as a react child when trying to render component based off of AsyncStorage React-Native
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。