繁体   English   中英

类型错误:arr.map 不是 function

[英]TypeError: arr.map is not a function

我正在使用 reactjs 并且在尝试显示来自服务器的数据时似乎无法阻止此错误。 我的 axios 文件:

import axios from "axios";
import {BASE_URL} from "../config";

export const readLectures = () => {
    return axios
        .get(`${BASE_URL}/api/lectures/all`)
        .then(response => {
            return response.data;
        })
        .catch(error => {
            console.log(error);
        })

};

所以,function readLectures 返回了这个词的数组。 我应该如何编写 function updateLecture corectle 才能很好地工作。 我应该如何将数据从服务器传递到 setLection()? 请帮我。 非常感谢。

import { readLectures } from '../../../api/lectures';
const StudentsViewing = (props) => {
  const [lection, setLection] = useState([]);

  const updateLecture = () => {
    readLectures(setLection({lection}))
    }

  useEffect(() => {
    updateLecture()
  }, [])

  const renderLectures = (arr) => {
    return arr.map((item, index) => {

      return (
        <CardItem item={item} />
      )
    })

  }

  const lectionCard = renderLectures(lection);

  const settings = {
    dots: false,
    infinite: false,
    speed: 900,
    slidesToShow: 4,
    slidesToScroll: 4
  };

  return (
      <Slider {...settings}>
        {lectionCard}
      </Slider>
  )
}

export default StudentsViewing;

readLectures function 返回一个 promise,因此您可以在then回调中获取预期的array 见下文:

const updateLecture = () => {
    readLectures().then(lection => setLection(lection))
}

或者使用async/await语法:

const updateLecture = async () => {
    setLocation(await readLectures())
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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