开发者问题收集

在 React 的 useEffect() 中获取数据返回错误

2022-10-11
622

我试图显示如下数据:

import React, {useEffect} from 'react'
    const Slider = ({ getData }) => {
        
    useEffect(() => {
       getData.map(item =>
         console.log("data : ", item)
       )
      }, []);
        
     return (
       <div className='slider__container'>
          // { listItems }  
       </div>
     )
   }
        
export default Slider

为了看得清楚,这里是我调用组件的 app.js

import React, { useState, useEffect } from 'react';
import Slider from './Slider';
import './App.css';

function App() {
  const [loadSlide, setLoadSlide] = useState(0);
  const [data, setData] = useState();
  const handleclick = () => {
    setLoadSlide(loadSlide + 1)
  }

useEffect(() => {
    handleclick();
    fetch('/data.json')
    .then((response) => response.json())
    .then((json) =>  {
        setData(json.lvmh.slider)
        // console.log(json.lvmh.slider)
    });
}, [1]);

  return (
    <div className="App">
      <Slider title={`titre: ${loadSlide}`} getData={ data } />
    </div>
  );
}

export default App;

我的 json 如下所示:

"lvmh": {
      "slider": [
         {
            "id": 1,
            "progressBar": "01 / 07 Inspirationd",
            "title": "Are you looking for a perfume",
            "img": "https://wallpapercave.com/w/wp8671030",
            "slider": [
               { "type": "Woman" },
               { "type": "Mixte" }]
         },...

在 chrome 控制台中,它显示 Uncaught TypeError: Cannot read properties of undefined (reading 'map') ,有时显示 undefined

2个回答
//check getData is an array
const getData = [1, 2, 3, 4, 5]
  if(Array.isArray(getData)) {
    getData.map(item => console.log(item))
}
Ankur Sharma
2022-10-11

setState 应该是这样的: useState([]);

import React, { useState, useEffect } from 'react';
    import Slider from './Slider';
    import './App.css';
    
    function App() {
      const [loadSlide, setLoadSlide] = useState(0);
      const [data, setData] = useState([]);
      const handleclick = () => {
        setLoadSlide(loadSlide + 1)
      }
    
    useEffect(() => {
        handleclick();
        fetch('/data.json')
        .then((response) => response.json())
        .then((json) =>  {
            setData(json.lvmh.slider)
            // console.log(json.lvmh.slider)
        });
    }, [1]);
    
      return (
        <div className="App">
          <Slider title={`titre: ${loadSlide}`} getData={ data } />
        </div>
      );
    }
    
    export default App;
mitsu
2022-10-11