操纵 api 以显示来自单击元素的数据

因此,我正在学习 React 并正在构建一个使用 Marvel api 来显示英雄信息的应用程序。现在我有一个页面显示所有英雄的图像和名字。我想知道如何操作 API,以便在单击英雄图片时将我带到包含 API 中包含的更多详细信息(描述、系列列表等)的页面。我可能必须为此使用状态,但我真的不知道如何处理这种情况。这是我得到的代码:


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

import "../App.css";

import Heroes from './Heroes';


const FetchApi = () =>{


 const apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';

 const public_key = 'xxxxxxxxxxxxxxxxxxxxxxxxx'

 const md = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

 const apiURL=`https://gateway.marvel.com:443/v1/public/charactersts=1&apikey=${public_key}&hash=${md}`


 const [heroes, setHeroes] = useState([])

 


  useEffect (()=>{

      getData();

  

},[])


      const getData = async()=>{

      const data = await fetch(apiURL)

      const response = await data.json()

      setHeroes(response.data.results)

      console.log(response.data.results)

  }


  return(


      <div className='App'>

  

          <input type='text' className='search-bar'/>

         <button className='search-button'>Search</button> 

            <div>

          {heroes.map(hero =>(

           <Heroes

           image = {hero.thumbnail.path+'.jpg'}

           title ={hero.name}


          />

       ))}

          </div>  

       

      </div>

  )

}

export default FetchApi;


qq_花开花谢_0
浏览 102回答 3
3回答

一只甜甜圈

首先,您需要在 Heros 映射组件上创建 onClick 事件,然后将其传递给 history,在 app.js 中推送和创建路由,然后将传递的路径作为 match.params。.....&nbsp;<div>{heroes.map(hero =>(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Heroes onClick={() => onHeroClick(hero)}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;image = {hero.thumbnail.path+'.jpg'}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;title ={hero.name}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp;))}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp;const onHeroClick = (hero) => {&nbsp; &nbsp;&nbsp;//&nbsp; hero must have a unique id/name here which u can pass to the linkhistory.push('/heros/' + hero.name)}在 app.js 上<Route path={'/hero/:heroname} />在显示英雄详细信息的新组件上:const Component2 = ({match}) => {match.params.heroname = a unique id/name u sent withhistory.push('/heros/' + hero.name)

紫衣仙女

"Id&nbsp;like&nbsp;to&nbsp;know&nbsp;how&nbsp;can&nbsp;I&nbsp;manipulate&nbsp;the&nbsp;api&nbsp;..."我认为您需要为此查看 Marvel API 文档。根据我的经验,API 通常带有特定的模式。举例来说,我们有一个图书馆书籍的 API:点击/booksURL 意味着您将获得图书馆中的所有书籍。结果肯定是array of objects.&nbsp;就像你和英雄们所拥有的一样。点击/books/43URL 意味着您将获得某本书的详细信息。在这里,它的书 ID 等于 43。结果应该是一个对象,其中包含该书的所有信息。这就是您正在寻找的。我没有使用也没有阅读过 Marvel API,但我相信它应该在文档中。要在您的 React App 中实现它,您绝对可以使用Sushilzzz中的示例。

人到中年有点甜

好吧,如果你想显示另一个关于英雄细节的页面,你可以通过路由 ex 传递英雄的名字:http://marvelheros/TonyStark 你可以通过编程重定向。&nbsp;https://dev.to/projectescape/programmatic-navigation-in-react-3p1l另一种方法是您可以使用弹出窗口来显示英雄详细信息
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript