不断收到 TypeError:guide.map 不是函数

我似乎无法弄清楚为什么这不能正常工作。我已经查看了几个小时,我认为我已经正确设置了它,但它一直给我错误。我不确定我的状态设置是否错误。当我 console.log 它从 api 中获取示例数据并在控制台中显示它。


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

import styled from 'styled-components'

import axios from 'axios'

import GuideData from './Guides/GuideData.js'

import GuideLoader from './Guides/GuideLoader.js'


const GuideRender= styled.div`

display:flex;

flex-direction:column;

justify-content:space-between;

border: 5px black;

`


const HomePage = () => {


    const[guide, setGuide]=useState([]);

    const apiLink ='https://how-to-guide-unit4-build.herokuapp.com/api/guides/'



    useEffect(() => {

        axios

        .get(apiLink)

        .then(response => setGuide(response))

        .catch(err =>

            console.log(err));

    }, []);

    console.log(guide)


    if (!guide) return <GuideLoader />;



    return (

        <div>

        <GuideRender>

            {guide.map(item => (

                <GuideData key={item} item={item} />

            ))} 

        </GuideRender>

        <div>

            <button>Create Article</button>

        </div>

        </div>

    )

}



export default HomePage

http://img3.mukewang.com/62d954230001517e09710815.jpg

HUX布斯
浏览 109回答 2
2回答

jeck猫

给你,清理一下你的useEffect功能。错误是您只设置了response,而不是response.data。&nbsp; const HomePage = () => {&nbsp; const [guide, setGuide] = useState([]);&nbsp; const [loading, setLoading] = useState(true);&nbsp; const apiLink = "https://how-to-guide-unit4-build.herokuapp.com/api/guides/";&nbsp; useEffect(() => {&nbsp; &nbsp; fetchData();&nbsp; }, []);&nbsp; const fetchData = async () => {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; const response = await axios.get(apiLink);&nbsp; &nbsp; &nbsp; setGuide(response.data);&nbsp; &nbsp; &nbsp; setLoading(false);&nbsp; &nbsp; } catch (error) {&nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; }&nbsp; };&nbsp; if (loading) {&nbsp; &nbsp; return "Loading...";&nbsp; }&nbsp; console.log(guide);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <GuideRender>&nbsp; &nbsp; &nbsp; &nbsp; {guide.map(item => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <GuideData key={item} item={item} />&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; </GuideRender>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <button>Create Article</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; );};

慕少森

你的代码看起来不错。您可以使用可选链接来避免组件在 API 集成时中断。工作沙箱
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript