简体   繁体   中英

Is the array undefined because component is rendering before data is loaded?

I've imported an array of objects from a seperate js file into my main app.js file in react. I want to map through the array and pass the object values as props to a seperate component. When I run this code the pupils array is coming back as undefined.

I'm new to react and js, this is a learning project I'm working on usings functional components.

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import { pupils } from "./pupils"
import PupilCard from "./Components/PupilCard";


const App = () => {



 return (<div>
    {pupils.map(pupil => 
    <PupilCard 
        firstname={pupil.firstname} 
        surname={pupil.surname}
        photo={pupil.photo}
        behaviourPoints={pupil.behaviourPoints}
        assessmentOne={pupil.assessmentOne}
        assessmentTwo={pupil.assessmentTwo}
        assessmentThree={pupil.assessmentThree}  
     />)}

 </div>)}

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();


pupils.js example

const pupils = [
    {
        firstname: "Name",
        surname: "Name",
        photo:"./assets/pupilPhotos/user.png",
        behaviourPoints: 25,
        assessmentOne:70,
        assessmentTwo:60,
        assessmentThree:80        
    },
 {
        firstname: "Name",
        surname: "Name",
        photo:"./assets/pupilPhotos/user.png",
        behaviourPoints: 25,
        assessmentOne:70,
        assessmentTwo:60,
        assessmentThree:80        
    }]

To use "pupils" this way it must be exported as export const pupils =... . Maybe you exporting it like export default... then it should be imported without destructuring import pupils from './pupils' this cheatsheet may help you to better understand imports/exports

You need to export your array in pupils.js in order to import it in another file. If you use 'export default' you have to remove the curly braces around pupils in the import statement, Or you can just export as named and keep the curly braces in the import. That should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM