首页 文章

将使用axios获取的json数据拆分为可重定向到页面的可单击列表项

提问于
浏览
1

Noob做出反应,以及与网络开发有关的所有事情 . 我正在尝试在Navbar中创建一个列表,其中包含将用户重定向到新页面的按钮 . 我从JSON文件中获取运动,我有下面的代码来减少/摆脱所有重复项 . 我现在的问题是创建列表的最佳做法,例如带有按钮的导航栏,每个按钮可以获得一项运动 . 我在总共有5项运动,我不知道如何将它们从SportList.js文件中分离出来 . 我的目标是以某种方式将它们附加到图标(如足球足球),将用户发送到足球页面(在那里你可以看到所有足球比赛) . 不确定从哪里开始 .

我希望我的问题不是混淆,英语不是我的第一语言 . 任何帮助和/或提示都很棒 . 问我是否没有意义,我会尝试重新解释这个问题 . 谢谢!

import React, { Component } from 'react'
import axios from 'axios'

class SportList extends Component {
  state = {
    posts: []
  }
  componentDidMount(){
    axios.get('https://data.json')
      .then(res => {
        this.setState({
          posts: res.data
        });
      })
  }
  render() {
    const { posts } = this.state;
    const uniquePosts = Object.values(posts.reduce((r,c) => { 
      r[c.sport] = c 
      return r
    }, {}))
    const postList = uniquePosts.length ? (
        uniquePosts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (<div>No Sports Available</div>)
    return (<div>{postList}</div>);
  }
}

export default SportList

1 回答

  • 2

    你需要安装两个包react-router-dom和lodash .

    在api调用之后,一旦获得数据 . 获取运动名称,为运动创建每个组件 . 将数据传递给每个组件 .

    NoteSince i don't have the api, i have used to get it from a file, so you can call the api in the componentDidMount and set the data to state.

    还可以使用Route组件来根据每个组件负载呈现数据 .

    我希望这能解决问题 . 如果发生任何问题,请告诉我 .

    // App.js
    
    import React, { Component } from 'react';
    import './App.css';
    import Aux from './Aux';
    import { BrowserRouter, Switch, Route } from 'react-router-dom';
    import Data from './Data';
    import FootBall from './FootBall';
    import EachNavLink from './EachNavLink';
    import {groupBy} from 'lodash'
    
    class App extends Component {
    
      state = {
        apiData: Data
      }
    
      getData = (sport) => {
        let data = groupBy(this.state.apiData, "sport")
        return data[sport];
      }
    
      renderTabs = () => {
        const { apiData } = this.state
        const sports = Array.from(new Set(apiData.map(o => o.sport)))
    
        const tabs = sports.map((item, index) => {
          return (
            <EachNavLink
              key={index}
              href={`/${item}`}
              name={item}
            />
          )
        })
        return tabs
      }
    
    
      render() {
        const { apiData } = this.state
        return (
          <BrowserRouter>
            <Aux>
              <Aux>
                {
                  apiData.length > 0 ?
                    this.renderTabs()
                    :
                    <p>Data is Loading... Please wait.</p>
                }
              </Aux>
              <div className="content">
                <Switch>
                  <Route path="/FOOTBALL" render={(routeProps) => (<FootBall {...routeProps} data={apiData.length > 0 ? this.getData("FOOTBALL") : []} />)} />
                </Switch>
              </div>
            </Aux>
          </BrowserRouter>
        );
      }
    }
    
    
    
    export default App;
    
    
    // Data.js
    
    const data = [
        {
            "awayName": "Panthrakikos Komotini",
            "createdAt": "2015-12-18T12:30:39.228Z",
            "group": "Greek Cup",
            "homeName": "Chania FC",
            "id": 1002916450,
            "name": "Chania FC - Panthrakikos Komotini",
            "objectId": "1UaQjc7lIb",
            "sport": "FOOTBALL",
            "country": "ENGLAND",
            "state": "STARTED"
        },
        {
            "awayName": "PAOK Thessaloniki",
            "createdAt": "2015-12-18T12:30:39.234Z",
            "group": "Greek Cup",
            "homeName": "Olympiakos Volos",
            "id": 1002916451,
            "name": "Olympiakos Volos - PAOK Thessaloniki",
            "objectId": "UPJ240T2Qj",
            "sport": "FOOTBALL",
            "country": "FRANCE",
            "state": "STARTED"
        },
        {
            "awayName": "Ukraine U18",
            "createdAt": "2015-12-18T12:30:39.244Z",
            "group": "Under 18",
            "homeName": "Israel U18",
            "id": 1003022920,
            "name": "Israel U18 - Ukraine U18",
            "objectId": "fZZUhitsVt",
            "sport": "FOOTBALL",
            "country": "SWEDEN",
            "state": "STARTED"
        },
        {
            "awayName": "Stade Gabesien",
            "createdAt": "2015-12-18T12:30:39.249Z",
            "group": "Ligue 1",
            "homeName": "CA Bizertin",
            "id": 1003015194,
            "name": "CA Bizertin - Stade Gabesien",
            "objectId": "Bf52z7GIut",
            "sport": "FOOTBALL",
            "country": "SWEDEN",
            "state": "STARTED"
        },
        {
            "awayName": "AS de la Marsa",
            "createdAt": "2015-12-18T12:30:39.255Z",
            "group": "Ligue 1",
            "homeName": "Club Africain",
            "id": 1003015197,
            "name": "Club Africain - AS de la Marsa",
            "objectId": "sFjPkmljKv",
            "sport": "FOOTBALL",
            "country": "ENGLAND",
            "state": "STARTED"
        },
        {
            "awayName": "Kastamonuspor",
            "createdAt": "2015-12-18T12:30:39.261Z",
            "group": "T\u00fcrkyie Kupasi",
            "homeName": "Kar\u015f\u0131yaka",
            "id": 1003016331,
            "name": "Kar\u015f\u0131yaka - Kastamonuspor",
            "objectId": "cRqV2RTmsu",
            "sport": "FOOTBALL",
            "country": "FRANCE",
            "state": "FINISHED"
        },
        {
            "awayName": "Allen, Gareth",
            "createdAt": "2015-12-18T12:30:39.266Z",
            "group": "German Masters Qualifiers",
            "homeName": "Ding Junhui",
            "id": 1003018193,
            "name": "Ding Junhui - Allen, Gareth",
            "objectId": "nPuz011p0W",
            "sport": "SNOOKER",
            "country": "SWEDEN",
            "state": "NOT_STARTED"
        },
        {
            "awayName": "Lines, Peter",
            "createdAt": "2015-12-18T12:30:39.272Z",
            "group": "German Masters Qualifiers",
            "homeName": "Trump, Judd",
            "id": 1003018186,
            "name": "Trump, Judd - Lines, Peter",
            "objectId": "CSJn3kZhdx",
            "sport": "SNOOKER",
            "country": "ENGLAND",
            "state": "NOT_STARTED"
        },
        {
            "awayName": "SKIF-Krasnodar",
            "createdAt": "2015-12-18T12:30:39.278Z",
            "group": "Cup",
            "homeName": "Dinamo Astrakhan",
            "id": 1003027200,
            "name": "Dinamo Astrakhan - SKIF-Krasnodar",
            "objectId": "enCbqOuRLr",
            "sport": "HANDBALL",
            "country": "SWEDEN",
            "state": "STARTED"
        },
        {
            "awayName": "THK Tver",
            "createdAt": "2015-12-18T12:30:39.283Z",
            "group": "VHL",
            "homeName": "Zauralie Kurgan",
            "id": 1002988754,
            "name": "Zauralie Kurgan - THK Tver",
            "objectId": "7HWfuCIMlp",
            "sport": "ICE_HOCKEY",
            "country": "ENGLAND",
            "state": "STARTED"
        },
        {
            "awayName": "Doumbia, SReboul, F",
            "createdAt": "2015-12-18T12:30:39.289Z",
            "group": "Nigeria",
            "homeName": "Harris, L G MMaamoun, K M",
            "id": 1003026313,
            "name": "Harris, L G MMaamoun, K M - Doumbia, SReboul, F",
            "objectId": "JxrZyQKTrw",
            "sport": "TENNIS",
            "country": "FRANCE",
            "state": "STARTED"
        },
        {
            "awayName": "Halebian, Alexios",
            "createdAt": "2015-12-18T12:30:39.294Z",
            "group": "Dominican Republic",
            "homeName": "Bangoura, Sekou",
            "id": 1003026667,
            "name": "Bangoura, Sekou - Halebian, Alexios",
            "objectId": "tALMRNqAxD",
            "sport": "TENNIS",
            "country": "SWEDEN",
            "state": "NOT_STARTED"
        },
        {
            "awayName": "Roberts, Justin",
            "createdAt": "2015-12-18T12:30:39.300Z",
            "group": "Dominican Republic",
            "homeName": "Pla Malfeito, Jaume",
            "id": 1003026666,
            "name": "Pla Malfeito, Jaume - Roberts, Justin",
            "objectId": "KGA9nqYAJl",
            "sport": "TENNIS",
            "country": "ENGLAND",
            "state": "FINISHED"
        },
        {
            "awayName": "Mridha, J",
            "createdAt": "2015-12-18T12:30:39.306Z",
            "group": "Qatar",
            "homeName": "Clayton, Scott",
            "id": 1003026476,
            "name": "Clayton, Scott - Mridha, J",
            "objectId": "utc63de1Fl",
            "sport": "TENNIS",
            "country": "FRANCE",
            "state": "STARTED"
        },
        {
            "awayName": "Kania, PKerkhove, L",
            "createdAt": "2015-12-18T12:30:39.311Z",
            "group": "Ankara",
            "homeName": "Buyukakcay, CKrunic, A",
            "id": 1003026234,
            "name": "Buyukakcay, CKrunic, A - Kania, PKerkhove, L",
            "objectId": "mTVUIuYdbF",
            "sport": "TENNIS",
            "country": "SWEDEN",
            "state": "NOT_STARTED"
        },
        {
            "awayName": "Chernetsova, DPerper, A",
            "createdAt": "2015-12-18T12:30:39.317Z",
            "group": "El Kantaoui",
            "homeName": "Baskova, DPodlinska, M",
            "id": 1003026673,
            "name": "Baskova, DPodlinska, M - Chernetsova, DPerper, A",
            "objectId": "heL53W56d2",
            "sport": "TENNIS",
            "country": "FRANCE",
            "state": "STARTED"
        },
        {
            "awayName": "Njoze, M",
            "createdAt": "2015-12-18T12:30:39.322Z",
            "group": "El Kantaoui",
            "homeName": "Stoilkovska, M",
            "id": 1003026214,
            "name": "Stoilkovska, M - Njoze, M",
            "objectId": "gldlV9xhi2",
            "sport": "TENNIS",
            "country": "SWEDEN",
            "state": "STARTED"
        },
        {
            "awayName": "Haas, Barbara",
            "createdAt": "2015-12-18T12:30:39.328Z",
            "group": "Navi Mumbai",
            "homeName": "Jia-Jing Lu",
            "id": 1003026299,
            "name": "Jia-Jing Lu - Haas, Barbara",
            "objectId": "V6Qsm2Wlms",
            "sport": "TENNIS",
            "country": "ENGLAND",
            "state": "FINISHED"
        }
    ]
    
    export default data
    
    
    // Aux.js
    
    
    const aux = ({children}) => children
    
    export default aux
    
    // EachNavLink.js
    
    import React from 'react';
    import {NavLink} from 'react-router-dom';
    
    const eachNavLink = ({href,name}) => {
      return(
        <div>
         <NavLink
          to={href}
          activeClassName="active"
         >  
         {name}
         </NavLink>
        </div>
      )
    }
    
    
    export default eachNavLink
    
    
    // FootBall.js
    
    import React from 'react';
    
    const football = (props) => {
        const { data } = props
        return (
            data.map((item, index) => {
                return (
                    <div key={index}>
                        <ul>
                            <li>Away Name: {item.awayName}</li>
                            <li>Country: {item.country}</li>
                            <li>Group: {item.group}</li>
                        </ul>
                    </div>
                )
            })
        )
    }
    
    export default football
    

相关问题