简体   繁体   English

如何从特定的 JSON 文件中获取数据?

[英]How to fetch data from a specific JSON file?

I have one issue with fetching data from a json file.我在从 json 文件中获取数据时遇到一个问题。

The json file has some sub arrays and I want to map it. json 文件有一些子 arrays,我想要 map。 I created a codesandbox page and need help for mapping the related data: https://codesandbox.io/s/json-data-fetch-c00rf我创建了一个 codesandbox 页面,需要帮助来映射相关数据: https://codesandbox.io/s/json-data-fetch-c00rf

When you open the link you will see that I have used React fetching with useEffect but it is not restricted with that, that means you can use another thing.当您打开链接时,您会看到我使用了 React 抓取和 useEffect 但它不受此限制,这意味着您可以使用其他东西。

The json data coming from here: https://web-coding-challenge.vercel.joyn.de/api/blocks json数据来自这里: https://web-coding-challenge.vercel.joyn.de/api/blocks

Here is the code as well:这也是代码:

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [todos, setTodos] = React.useState<any[]>([]);

  React.useEffect(() => {
    fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
      .then((results) => results.json())
      .then((data) => {
        setTodos(data);
      });
  }, []);

  return (
    <div className="App">
      {todos.map((post: any) => (
        <div>
          <h1>{post.id}</h1>
          <h2>{post.assets.primaryImage.url}</h2>
        </div>
      ))}
    </div>
  );
}

You can map through the post.assets and return your required jsx你可以通过post.assets返回你需要的 jsx

For an example here I'm listing all the urls in a list举个例子,我列出了列表中的所有网址

    return (
    <div className="App">
      {todos.length && todos.map((post: any) => (
        <div>
          <h2>{post.id}</h2>
          <ul>
          {post.assets.map((asset: any, index: number)=>{
            return (
              <li key={index}>{asset.primaryImage.url}</li>
            )
          })}
          </ul>
        </div>
      ))}
    </div>
  );

sandbox 沙箱

The response constains assets as an nested array.响应包含资产作为嵌套数组。 So you can use reduce and get all the elements in one array and then iterate it to create list所以你可以使用 reduce 并获取一个数组中的所有元素,然后迭代它来创建列表

 import "./styles.css"; import React, { useState, useEffect } from "react"; export default function App() { const [todos, setTodos] = React.useState<any[]>([]); React.useEffect(() => { fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`).then((results) => results.json()).then((data) => { const responseData = data.reduce((acc:any,curr:any)=>{ const assets = curr.assets; acc.push(...assets) return acc; },[]) setTodos(responseData); }); }, []); return ( <div className="App"> {todos.map((post: any) => ( <div> <h1>{post.id}</h1> <h2>{post.primaryImage.url}</h2> </div> ))} </div> ); }

截屏

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM