【问题标题】:How to pass state/data from one component to another in React.js (riot api specifically)如何在 React.js 中将状态/数据从一个组件传递到另一个组件(特别是 riot api)
【发布时间】:2021-06-03 03:36:31
【问题描述】:

我正在尝试从一个组件的 API 调用中提取信息,然后在单独组件的另一个 API 调用中使用该数据。但是,我不确定如何在第二个组件中导出和使用来自第一个 API 调用的数据。

App.js

import './App.css';
import FetchMatch from './fetch-match/fetch.match';
import FetchPlayer from './fetch-player/fetch.player';

function App() {
  return (
    <div className="App">
        <h1>Hello world</h1>
        <FetchPlayer></FetchPlayer>
        <FetchMatch></FetchMatch>
        
    </div>
  );
}

export default App;

fetch.player 然后进行第一次 API 调用以获取用户特定 ID,该 ID 将在第二次 API 调用中使用,以获取用户匹配历史记录。

fetch.player.js

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const FetchPlayer = () => {

  const [playerData, setPlayerData] = useState([]);
  
  const userName = 'users name';
  const userTagLine = '1234';
  const apiKey = '???';
  
  useEffect( () => {
    axios.get(`https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/${userName}/${userTagLine}?api_key=${apiKey}`)
    .then(response => {
      console.log(response.data)
      setPlayerData([response.data])
    })
    .catch(error => console.log(error))
  }, []);


  return (
    <div>
      {playerData.map( data => (
        <div>
          <p>{data.puuid}</p>
          <p>{data.gameName}#{data.tagLine}</p>
        </div>
      ))}
    </div>
    )
}

export default FetchPlayer;

这里不多,但以防万一......

fetch.match.js

import React, { useState } from 'react';

// Somehow take in the puuid set in the state of fetch.player to make a second API call below
const FetchMatch = () => {

  const [matchData, setMatchData] = useState([]);

  return (
    <div>
      // players match list goes here
    </div>
    )
}

export default FetchMatch;

我不确定我是否应该创建一个单独的函数来允许我创建常量来处理单个文件中的两个 API 调用。或者,如果有一种方法可以将 fetch.player 中的状态作为道具传递给 App.js 中的 fetch.match。我试过做前者,但它要么不起作用,要么我弄乱了语法(很可能是这个)

【问题讨论】:

    标签: javascript reactjs react-props react-component riot-games-api


    【解决方案1】:

    如果你在父组件中同时渲染两个组件,它们被称为兄弟组件。

    兄弟组件中的数据共享可以通过多种方式(Redux、Context 等)完成,但最简单和最简单的方式(没有 3rd 方 API 的最基本方式)涉及使用 parent 作为中间组件。

    首先,您在父组件中创建状态并将其作为道具提供给需要来自其兄弟的数据的子组件(在您的情况下是 FetchMatch)。

    import React from 'react';
    import './App.css';
    import FetchMatch from './fetch-match/fetch.match';
    import FetchPlayer from './fetch-player/fetch.player';
    
    function App() {
      const [data,setData] = React.useState();
    
      return (
        <div className="App">
            <h1>Hello world</h1>
            <FetchPlayer></FetchPlayer>
            <FetchMatch data={data} ></FetchMatch>
            
        </div>
      );
    }
    
    export default App;
    

    提供 setData 函数作为子组件的道具,该子组件将获取初始 API(在您的情况下是 FetchPlayer

    <FetchPlayer onPlayerLoad={(data) => setData(data)} />
    

    然后,在该子组件中,当您完成调用 API 并获得结果时,将该结果传递给 onPlayerLoad 函数,该函数将调用 setData 函数并将结果作为参数。这将导致第二个FetchMatch 组件的状态更改和重新渲染,为 props 数据提供 API 结果。

    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    const FetchPlayer = ({onPlayerLoad}) => {
    
      const [playerData, setPlayerData] = useState([]);
      
      const userName = 'users name';
      const userTagLine = '1234';
      const apiKey = '???';
      
      useEffect( () => {
        axios.get(`https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/${userName}/${userTagLine}?api_key=${apiKey}`)
        .then(response => {
          console.log(response.data)
          setPlayerData([response.data])
          onPlayerLoad(response.data)
        })
        .catch(error => console.log(error))
      }, []);
    
    return <></>;
    

    进入 FetchMatch,您将在第二次渲染中获得数据。

    import React, { useState } from 'react';
    
    // Somehow take in the puuid set in the state of fetch.player to make a second API call below
    const FetchMatch = ({data}) => {
    
      const [matchData, setMatchData] = useState([]);
    
      //console.log(data);
      return (
        <div>
          // players match list goes here
        </div>
        )
    }
    
    export default FetchMatch;
    

    现在,您可以对第二个组件中的共享数据做任何您想做的事情,在您的情况下是触发器匹配 API。 ?

    【讨论】:

    • 有一种感觉,它必须通过父母深入到孩子身上。非常感谢您的帮助,让它快速轻松地工作!。
    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2021-01-02
    • 2020-03-12
    • 2019-12-11
    • 1970-01-01
    • 2018-05-02
    • 2018-09-28
    • 2018-11-03
    相关资源
    最近更新 更多