Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

reactjs - Unable to display an API data using map function on Material UI tabs

I'm new to this programming world. Can anyone please help me on this.

I have implemented Material UI's tabs successfully by hard-coding the content, but when I tried to make my hard coded tabs with a .map function to populate the content from a data source (json), it no longer works. The tab displays nothing.

Here are the codes,

Planet component:

import React from 'react';

function Planet(props) {

    return (
        <ul>
            <li>{props.name}</li>
        </ul>
    );
}

export default Planet;

Planets component:

import React, { useEffect, useState} from 'react';
import Planet from './Planet';

function Planets(props) {

    const [planets, setPlanets] = useState([]);
    
    useEffect(() => {
        getPlanets();
    }, []);

    const getPlanets = async () => {
        const response = await fetch("https://assignment-machstatz.herokuapp.com/planet");
        const data = await response.json();
        setPlanets(data); 
    }

    return (
        <div>
            {planets.map((planet, index) => {
                return (
                <Planet key={index} name={planet.name} />
                );
        })} 
        </div>
    );

}

export default Planets;

App component:

import React, { useState } from 'react';
import { AppBar, Tabs, Tab } from '@material-ui/core';
import Planet from './Planet';
import Favplanets from './Favplanets';

function App() {

    const [selectedTab, setSelectedTab] = useState(0);

    function handleChange (event, newValue) {
        setSelectedTab(newValue);
    }

    return (
        <>
            <AppBar position="static">
            <Tabs value={selectedTab} onChange={handleChange} >
            <Tab label="Planets" />
            <Tab label="Favourite Planets" />
            </Tabs>
        </AppBar>
        {selectedTab === 0 && <Planet />}
        {selectedTab === 1 && <Favplanets />}
        </>
    );
}

export default App;

Thanks for your help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...