问题是在use()方法中显示useState中的数据

问题描述 投票:0回答:2

我正在尝试在React中使用useState呈现来自GET请求的数据。我可以控制台记录我的数据,其结构如下:

{{id:1,标题:“ title”,date_of_show:“ date”,预告片:“ Welcome to ...”,card_image:“ https://blahblahblah.jpg”,内容:“ asdfasd”}

我正在尝试获取此数据以替换return()中的硬编码数据。我尝试了几种不同的方法,如下面组件(episode = {data.id}和card_image = {data.card_image})中的“ episode”和“ card_image”道具所示。

但是,我无法通过return()方法中的useState访问数据。我究竟做错了什么?任何帮助/建议都将不胜感激。

import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';


function App(){
  const [data, setData] = useState([]);

  useEffect(async () => {
    const fetchData = async () => {
    const result = await axios(
      'http://localhost:5000/episode',
    );

    setData(result.data);
    console.log(result.data[0]);
  };
  fetchData();
}, []);

    return (
      <div className="episode-app-page" style={{ color: 'white' }}>
        <Logo />    
        <Router>
          <Switch>
            <Route exact path='/' render={() =>
              <div id="link-container">

                <Link to="/e1">
                  <Post
                    episode={data.id}
                    card_image={data.card_image}
                    title="title goes here"
                    date_of_show="April 20, 2020"
                    teaser="This is the..." />
                </Link>

              </div>
            } />
          </Switch>
        </Router>
        <MeetingFormModal />
      </div>
    );
  }



export default App;


javascript reactjs
2个回答
0
投票
如果您只想使用api响应的第一个元素,请执行以下操作:

<Post episode={data[0].id} card_image={data[0].card_image} title="title goes here" date_of_show="April 20, 2020" teaser="This is the..." />

您也可以使用data.map并遍历数组并渲染所有<Post>

也要注意的一点:不要将useEffect的回调函数指定为async。 useEffect的返回类型是一个函数。如果我们使用异步,那么它将返回一个promise。

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.