我如何使用 props React js 通过 API 调用来渲染组件

我正在尝试渲染一个使用我传递的 prop 调用 api 的组件,但出现此错误:错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染子集合,请改用数组。


还有其他人说它无法读取 null 的属性映射,这是我的代码


import React, { useEffect } from "react";


const GetLeagues = async (country) => {

    const url = `https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${country}&s=Soccer`;

    const res = await fetch(url);

    const { countrys } = await res.json();


    return (

        <div>

            <ul>

                {countrys.map((country, i) => {

                    return <li key={i}>{country.strLeague}</li>;

                })}

            </ul>

        </div>

    );

};


const Leagues = () => {

    useEffect(() => {

        GetLeagues();

    }, []);


    return (

        <div>

            <GetLeagues country={"Spain"} />

        </div>

    );

};


export default Leagues;


达令说
浏览 165回答 3
3回答

慕娘9325324

您不应该在组件主体中产生副作用,您应该使用useEffect副作用来产生副作用,因此您不应该创建组件async,而是可以将函数定义为异步,使用它们useEffect然后设置状态。function Leagues({ country }) {&nbsp; const [countryData, setCountryData] = React.useState([]);&nbsp; React.useEffect(() => {&nbsp; &nbsp; async function getCountries() {&nbsp; &nbsp; &nbsp; const url = `https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${country}&s=Soccer`;&nbsp; &nbsp; &nbsp; const res = await fetch(url);&nbsp; &nbsp; &nbsp; const { countrys } = await res.json();&nbsp; &nbsp; &nbsp; setCountryData(countrys);&nbsp; &nbsp; }&nbsp; &nbsp; getCountries();&nbsp; }, [country]);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; {countryData.map((country, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return <li key={i}>{country.strLeague}</li>;&nbsp; &nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(&nbsp; <Leagues country="Spain"&nbsp; />,&nbsp; document.getelementById("root"));由于async代码片段中不支持函数,因此这里是带有.thenPromise 链的工作版本。function Leagues({ country }) {&nbsp; const [countryData, setCountryData] = React.useState([]);&nbsp; React.useEffect(() => {&nbsp; &nbsp; const url = `https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${country}&s=Soccer`;&nbsp; &nbsp; fetch(url)&nbsp; &nbsp; &nbsp; .then((res) => res.json())&nbsp; &nbsp; &nbsp; .then(({ countrys }) => setCountryData(countrys));&nbsp; }, [country]);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; {countryData.map((country, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return <li key={i}>{country.strLeague}</li>;&nbsp; &nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(&nbsp; <Leagues country="Spain" />,&nbsp; document.getElementById("root"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script><div id="root" />

人到中年有点甜

这是组件,只需在应用程序中调用它,<Leagues c='Spain'/> 我调用参数c,因为country显然在countrys任何地方都不可读。import React, { useEffect, useState } from "react";const Leagues = ({c}) => {&nbsp; &nbsp; const [countrys, countrysSet] = useState(false);&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; countrysSet(false);&nbsp; &nbsp; &nbsp; &nbsp; const url = `https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?c=${c}&s=Soccer`;&nbsp; &nbsp; &nbsp; &nbsp; fetch(url).then( res => res.json()).then(countrysSet);&nbsp; &nbsp; }, [c]);&nbsp; &nbsp; if( countrys === false ) {&nbsp; &nbsp; &nbsp; &nbsp; return <p>loading...</p>;&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {countrys.map((country, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return <li key={i}>{country.strLeague}</li>;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );};export default Leagues;

ABOUTYOU

我认为你应该将该代码分解为几个部分。另外,您不能在函数体内进行 api 调用,否则每次重新渲染组件时它都会运行。让我用你的例子向你展示:import React, { useEffect, useState } from "react";&nbsp; &nbsp;const GetLeagues = async (country) => {&nbsp; &nbsp; &nbsp; &nbsp;// This helper function fetches your leagues&nbsp; &nbsp; &nbsp; &nbsp;const url = 'your url'&nbsp; &nbsp; &nbsp; &nbsp;const res = await fetch(url);&nbsp; &nbsp; &nbsp; &nbsp;const { countries } = await res.json();&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return countries;&nbsp; &nbsp;};&nbsp; &nbsp;&nbsp; &nbsp;const Leagues = () => {&nbsp; &nbsp; &nbsp; &nbsp;const [leagues, setLeagues] = useState([]);&nbsp; &nbsp; &nbsp; &nbsp;useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; async function init() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Declaring an extra function as useEffect&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // cannot be async.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const countries = await GetLeagues();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setLeagues(countries);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;init();&nbsp; &nbsp; &nbsp; &nbsp;}, []);&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {leagues.map((country, i) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return <li key={i}>{country.strLeague}</li>;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp; &nbsp;);&nbsp; &nbsp;};&nbsp; &nbsp;export default Leagues;请注意,现在“GetLeagues”只是一个实用函数,而不是 React 组件。这样就可以重复使用而不渲染任何东西。此外,您的“Leagues”组件会处理渲染自身所需的所有操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript