亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不斷收到 TypeError:guide.map 不是函數

不斷收到 TypeError:guide.map 不是函數

HUX布斯 2022-07-21 21:26:33
我似乎無法弄清楚為什么這不能正常工作。我已經查看了幾個小時,我認為我已經正確設置了它,但它一直給我錯誤。我不確定我的狀態設置是否錯誤。當我 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
查看完整描述

2 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

給你,清理一下你的useEffect功能。錯誤是您只設置了response,而不是response.data。


  const HomePage = () => {

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

  const [loading, setLoading] = useState(true);


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


  useEffect(() => {

    fetchData();

  }, []);


  const fetchData = async () => {

    try {

      const response = await axios.get(apiLink);

      setGuide(response.data);

      setLoading(false);

    } catch (error) {

      console.log(error);

    }

  };


  if (loading) {

    return "Loading...";

  }


  console.log(guide);

  return (

    <div>

      <GuideRender>

        {guide.map(item => (

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

        ))}

      </GuideRender>

      <div>

        <button>Create Article</button>

      </div>

    </div>

  );

};



查看完整回答
反對 回復 2022-07-21
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

你的代碼看起來不錯。您可以使用可選鏈接來避免組件在 API 集成時中斷。工作沙箱


查看完整回答
反對 回復 2022-07-21
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號