【问题标题】:Connecting 2 different arrays from the same external link - React hooks fetch从同一个外部链接连接 2 个不同的数组 - React hooks fetch
【发布时间】:2021-01-15 23:56:32
【问题描述】:

我能够获取数据什么 url,但问题是 url 分为几个数组,我需要获取数据并连接它们。

例子:

{
  "array1": [
    { "data1": {"name": "Name", "phone": "Phone"}}
    ]  
  "array2" : [
    { "data2": { "color": "Color", "car": "Car" } }
   ]
}

数据挂钩:

const userInfo = "URL";
 const [userData, setUserData] = useState([]);
    useEffect(() => {
        getUserInfo();
    }, []);

    const getUserInfo = async () => {
        const response = await fetch(UserInfo);
        const jsonData = await response.json();
        setUserData(jsonData);
    };

获取数据:

{ userData.data && userData.array1.map((array1, index)  =>
        <li key={"index" + index}  
                    <h5>{array1.data1.name} </h5>
        </li>
)}

我需要将 array1 中的名称与 array2 中的颜色连接起来,但我找不到方法。

预期输出:数据列表

【问题讨论】:

    标签: reactjs react-hooks fetch


    【解决方案1】:

    如果你能得到这两个数组,那么你可以用它来组合它们:

    const getUserInfo = async () => {
      const response = await fetch(UserInfo);
      const jsonData = await response.json();
      
       // this assumes `jsonData` in an object with keys `array1` and `array2`
       // if this is not the case, change `jsonData` below to the location of
       // those two arrays
       
      const { array1, array2 } = jsonData;
    
      const combinedArray = array1.map(({ data1 }, i) => ({
        ...data1,
        ...array2[i].data2 // assumes there is always a corresponding index in array 2
      }));
    
      // combinedArray will look like [ { name: 'Name', phone: 'Phone', color: 'Color', car: 'Car' } ] 
    
    
      setUserData(combinedArray);
    };
    ] 
    

    【讨论】:

    • 谢谢@James,但是如何将它们组合到我要获取数据的代码中?我的文件中没有任何 dummyData,但我从外部 URL 获取它。您可以看到我将链接存储在 userrInfo 下。
    • 我已经更新了答案,以展示我如何想象你会在你的代码中使用它
    • 谢谢詹姆斯,我做了一些更改,但您帖子背后的逻辑确实有效!
    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多