首页 > 解决方案 > 如何将数据传递给单个组件

问题描述

有时它会让你想放弃。看似简单解决的事情变成了大问题。

我在https://rickandmortyapi.com/上工作,我正在使用 react-router-dom。

我创建了所有字符的列表:

import React, { useState, useEffect } from 'react'
// styles
import { Wrapper, CardGrid, Grid, GridInfo } from './Cards.styles'
// API functions
import { getCharacters } from '../../API'

// import Link from react-router-dom
import { Link } from 'react-router-dom'

const Cards = () => {
  // state to keep track of the characters
  const [characters, setCharacters] = useState([])
  // state to keep track of character
  const [character, setCharacter] = useState([])

  // function to get the characters from the API
  const getCharactersFromAPI = async () => {
    try {
      const response = await getCharacters()
      setCharacters(response.results)
      return response
    } catch (error) {
      console.log(error)
    }
  }

  // function to get the single character from the API

  // const getCharacterFromAPI = async () => {
  //   try {
  //     const response = await getCharacter()
  //     setCharacter(response.results)
  //     return response
  //   } catch (error) {
  //     console.log(error)
  //   }
  // }

  // useeffect to update the characters
  useEffect(() => {
    getCharactersFromAPI()
    // getCharacterFromAPI()
  }, [])

  return (
    <Wrapper>
      <CardGrid>
        {characters.map((character) => {
          const {
            id,
            name,
            image,
            species,
            gender,
            // destucturing an object inside an array
            location,
          } = character
          return (
            <Grid key={id}>
              <img src={image} alt={name} />
              <GridInfo character={character}>
                <Link to={`/character/${id}`}>{name}</Link>
                <p className='first'>{species}</p>
                <p>{gender}</p>
                <p>{location.name}</p>
              </GridInfo>
            </Grid>
          )
        })}
      </CardGrid>
    </Wrapper>
  )
}
export default Cards

我的 API.js

// get all characters
export const getCharacters = async () => {
  return await fetch('https://rickandmortyapi.com/api/character')
    .then((response) => response.json())
    .then((json) => {
      ////   console.log(json)
      return json
    })
}

// Get a single character
export const getCharacter = async (id) => {
  return await fetch(`https://rickandmortyapi.com/api/character/${id}`)
    .then((response) => response.json())
    .then((json) => {
      ////   console.log(json)
      return json
    })
}

我创建了一个 SingleCharacter 组件来根据您的 id 显示每个字符。

单字符:

import React from 'react'
import { Wrapper } from './SingleCharacter.styles'

// show single character

const SingleCharacter = ({ character }) => (
  <Wrapper>
    <h1>Single</h1>
  </Wrapper>
)

export default SingleCharacter

我不知道如何使这个组件工作。

标签: reactjs

解决方案


在你的app.js文件中导入 SingleCharacter

//app.js

<Router>
//other routes
<Route exact path="/character/:characterId" component={SingleCharacter} />
</Router>

在您的 SingleCharacter 文件中

import {useState,useEffect} from 'react';
import {useParams} from "react-router-dom";
import { Wrapper } from './SingleCharacter.styles'


// show single character
const SingleCharacter=()=>{
const [character,setCharacter]=useState(null);
const {characterId}=useParams();
useEffect(()=>{
fetch(`https://rickandmortyapi.com/api/character/${characterId}`)
    .then((response) => response.json())
    .then((json) => {
      console.log(json);
      setCharacter(json);
    })
},[])
return(
 <Wrapper>
    <h1>Single</h1>
  </Wrapper>
)
}

export default SingleCharacter

推荐阅读