【问题标题】:Conditional rendering of React component if json key exists如果 json 键存在,则条件渲染 React 组件
【发布时间】:2020-09-27 12:52:58
【问题描述】:

我正在尝试有条件地渲染结果不佳的组件。我已经阅读了许多教程和 Stack Overflow 问题,但我无法完成这项工作。你能帮帮我吗?

条件组件是一个数据可视化的地理地图,只有在获取的 json 文件具有“code”键时才应该呈现。换句话说,我有几十个 json,其中一些包含地理地图信息,但不是全部。我一直在 jsx 中尝试布尔和不同类型的三元运算符,但是每次在侧边栏中单击无地图项时,React 都会尝试渲染 Map 子组件并给出“代码”(键)未定义的错误.这可能是什么原因?以下是我的代码:

App.js

function App() {
  const [files, setFiles] = useState([]);
  const [items, setItems] = useState([]);
  const [product_id, setProduct_id] = useState(13);
  const [mapCode, setMapcode] = useState(0);

  useEffect(() => {
    fetch("/sidebar")
      .then((res) => res.json())
      .then((data) => {
        setItems(data);
      });
  }, []);

  useEffect(() => {
    fetch(`/data/${product_id}`)
      .then((res) => res.json())
      .then((data) => {
        setFiles(data);
        if ("code" in data[0]) setMapcode(1);
        else setMapcode(0);
        console.log(mapCode);
      });
  }, [product_id]);

 function HandleSelection(e) {
    setProduct_id(e);
  }

如果获取的产品数据包含“code”键,则在 useEffect 中,每次在侧边栏中单击项目(产品)时,我都会更改 ma​​pCode。 console.log(mapCode) 给出了正确的结果。

下面是 App.js 的 return() 里面的基本代码。我尝试了几种方法来进行条件渲染。


<div className="col-6">
    <Files files={files} />
</div>
<div className="col-3">
         
    {/*Boolean(mapCode) && <Map files={files} />*/}
    {/*mapCode === true && <Map files={files} />*/}
    mapCode === true ? <Map files={files} /> : <div>No map</div>

</div>

我一直在想 useEffect 是否适合使用 setMapcode(0) 和 setMapcode(1)?

【问题讨论】:

    标签: reactjs components conditional-statements


    【解决方案1】:

    首先,您应该将布尔值设置为 isMapCode 而不是数字:

    const [isMapCode, setIsMapcode] = useState(false);
    
    useEffect(() => {
      fetch(`/data/${product_id}`)
        .then((res) => res.json())
        .then((data) => {
          setFiles(data);
          setIsMapcode(data[0].code !== undefined);
        });
    }, [product_id]);
    

    因此,您应该在范围内检查其值 ({}):

    <div className="col-3">
      {isMapCode ? <Map files={files} /> : <div>No map</div>}
    </div>
    

    请注意,您不需要其他状态,您可以检查您的files 状态:

    const isMapCodeAvailable = data[0].code !== undefined;
    <div className="col-3">
      {isMapCodeAvailable ? <Map files={files} /> : <div>No map</div>}
    </div>
    

    【讨论】:

    • 谢谢。我按照你的第一种方式setIsMapcode(data[0].includes("code")); 得到了一个错误:Unhandled Rejection (TypeError): data[0].includes is not a function。第二种方式const isMapCodeAvailable = files[0].includes("code"); 我得到了 TypeError: files[0] is undefined。不知何故,files[0] 不可用。在状态声明之后,我在函数 App() 的开头写了 const isMapCodeAvailable = files[0].includes('code');。找对地方了吗?
    • 您不需要复制粘贴解决方案,只需了解概念即可。我不知道你的数据是什么样子的。
    • 代码的主要问题是您没有在 JSX {} 中使用范围,我认为 if ("code" in data[0]) 是否 data[0] 是一个数组?或者您检查密钥是否存在
    • 我以为data[0]是一个数组,你可以像你一样做data[0].code !== undefined"code" in data[0]
    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2020-10-15
    • 2021-05-26
    • 2018-09-10
    相关资源
    最近更新 更多