简体   繁体   English

“TypeError:listOfTours.map 不是函数”,同时尝试在反应中显示获取的数据

[英]"TypeError: listOfTours.map is not a function" while trying to display fetched data in react

I'm struggling since two days on this and afters hours of trial and error I couldn't solve it.两天后我一直在苦苦挣扎,经过数小时的反复试验,我无法解决它。

What I'm trying to achieve is that I can display my fetched data, which I get from my backend.我想要实现的是我可以显示我从后端获取的获取的数据。 I saw several example on different websites, but I can't get it to work.我在不同的网站上看到了几个例子,但我无法让它工作。

Here is my code and the error I get:这是我的代码和我得到的错误:

function Tours({ isAuth: isAuth, component: Component, ...rest }) {
  const [listOfTours, setListOfTours] = useState([]);
  console.log(listOfTours);

  const getAllTours = () =>
    axios
      .get("/api/all-tours", {
        headers: {
          "x-access-token": localStorage.getItem("token"),
        },
      })
      .then((response) => {
        if (response.data.status === "error") {
          console.log(response.data.status);
        } else {
          setListOfTours(response.data);
        }
      });

  useEffect(() => {
    getAllTours();
  }, []);

  if (listOfTours.length > 0) {
    return (
      <div>
        <div className="tourDisplay">
          {listOfTours.map((tour) => {
            return (
              <div>
                <div>Tourname: {tour.tour_name}</div>
                <div>...other values</div>
              </div>
            );
          })}
        </div>
      </div>
    );
  } else {
    return (
      <div>
        <p>Loading...</p>
      </div>
    );
  }
}

export default withRouter(Tours);

TypeError: listOfTours.map is not a function
Tours
src/components/tours.js:32
  29 | if (listOfTours.length > 0) {
  30 |   return (
  31 |     <div>
> 32 |       <div className="tourDisplay">
     | ^  33 |         {listOfTours.map((tour) => {
  34 |           return (
  35 |             <div>

I think it has something to do with the asynchronous call and that.map can't process with empty array.我认为这与异步调用有关。map 无法处理空数组。 Therefor, I use the if statement in front of the return, but it also won't work.因此,我在 return 前面使用了 if 语句,但它也不起作用。

Does someone have any idea, or am I missing something?有人有任何想法,还是我错过了什么?

Try to make the getAllTours function as a Promise .尝试将getAllTours function 作为Promise

...
const [listOfTours, setListOfTours] = useState(null);

const getAllTours = async () => {
  try {
    // not sure if /api/all-tours is the proper API source
    const tours = await axios.get("/api/all-tours", {
        headers: {
          "x-access-token": localStorage.getItem("token"),
        },
    });

    // try to console.log here to make sure if the tours has responded successfully and what type of the tours.response.data has either object or array
    console.log(tours.response);
    console.log(typeof tours.response.data);

    // this seems to be tours.response without data
    if (tours.response.data) { // if (tours.response) {
      // if tours.response.data is a type string, then convert it to json object
      // setListOfTours(JSON.parse(tours.response.data));
      setListOfTours(tours.response.data);
      // setListOfTours(tours.response);
    }
  } catch (err) {
    console.error(err);
  }
}

  useEffect(() => {
    getAllTours();
  }, [getAllTours]);

  return (
    <div>
      {
        !listOfTours
          ? // loading div
          : <div className="tourDisplay">
          {listOfTours.length > 0 && listOfTours.map((tour) => {
            return (
              <div>
                <div>Tourname: {tour.tour_name}</div>
                <div>...other values</div>
              </div>
            );
          })}
        </div>
      }
    </div>
  );

If this doesn't work, please inspect the browser and go to the network tab, and then make sure the API worked properly.如果这不起作用,请检查浏览器和 go 到网络选项卡,然后确保 API 工作正常。

在此处输入图像描述

I don't know is your response.data array or not but if it is array I can write down some solutions and you can try all of them我不知道你的response.data是否是数组,但如果它是数组,我可以写下一些解决方案,你可以尝试所有这些

Check is array empty or not检查数组是否为空

as I can read in your code you check is your array true or false , which is wrong because javscript never reads array inside, you can try it on your own [] == [] is false so every time when you fetch data you keep your state empty because your if statement always returns false best way to check is array empty or not you can check its length正如我可以在您的代码中看到的那样,您检查的是您的数组true还是false ,这是错误的,因为 javscript 从不读取内部数组,您可以自己尝试[] == []是错误的,因此每次获取您保留的数据时你的 state 是空的,因为你的 if 语句总是返回false最好的检查方法是数组是否为空,你可以检查它的长度

wrong错误的

if (tours.response.data) { //it always returns false
    setListOfTours(tours.response.data);
}

and also will be better if you check is your response data undefined or not如果您检查您的响应数据是否undefined ,也会更好

better更好的

if (tours.response.data.length > 0 || !tours.response.data === undefined) {
    setListOfTours(tours.response.data);
}

Set default value before fetch在获取之前设置默认值

when you fetch data your state is always [] empty array and it never can read inside value if you will try to print in console listOfTours.tour_date you will get cannot read properties of null (reading 'tour_date') so before fetching the data create empty object with strins something like that当您获取数据时,您的 state 始终为[]空数组,如果您尝试在控制台listOfTours.tour_date中打印,它将永远无法读取内部值,您将无法读取 null 的属性(读取“tour_date”) ,因此在获取数据之前创建用类似的字符串清空 object

const defaultState = {
  "tour_date": "",
  "tour_distance": 0,
  "tour_duration": 0,
  "tour_elevation_down": 0,
  "tour_elevation_up": 0,
  "tour_name": "",
  "tour_sport": ""
}

const [listOfTours, setListOfTours] = useState([defaultState]);

and that code will relax your react and won't to pop up error, what I mentioned in start of null property并且该代码将放松您的反应并且不会弹出错误,我在 null 属性开头提到的

and you can make simple ternary operator to do not .map() elements if you state has default value如果您 state 具有默认值,您可以制作简单的三元运算符来不使用.map()元素

!listOfTours[0].tour_date === "" ?
listOfTours.map(each => {
   return <div>...</div>
}) : null

Spread Operator扩展运算符

the last way to fix that issue I don't think it will work but I will include that one too, if your response is really array and react can't recognize it you can you spread operator解决该问题的最后一种方法我认为它不会起作用,但我也会包括那个,如果您的响应真的是数组并且反应无法识别它,您可以传播运算符

if (tours.response.data.length > 0 || !tours.response.data === undefined) {
      setListOfTours([...tours.response.data]);
}

this code will put all the object in you array and it will update the state此代码会将所有 object 放入您的数组中,它将更新 state

If some of them will work let me know如果其中一些有效,请告诉我

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

相关问题 “TypeError:listOfTours.map 不是函数”当尝试 map over Array - "TypeError: listOfTours.map is not a function" when try to map over Array “Uncaught TypeError: .map is not a function” 试图显示获取的数据时 - "Uncaught TypeError: .map is not a function" while trying to display fetched data 反应来自 object TypeError 的显示数据:值 map 不是 function - React display data from object TypeError: value map is not a function 尝试将获取的json数据映射到React应用时,“状态”未定义 - “State” undefined when trying to map fetched json data into React app 类型错误:尝试显示来自 API 的数据时,无法在我的 React 应用程序中读取未定义的属性“映射”错误? - TypeError: Cannot read property 'map' of undefined' error in my React application when trying to display data from an API? map function on React state - state with fetched API data - map function on React state - state with fetched API data 在 React 中将获取的数据显示到表中 - Display fetched data into table in React 反应-TypeError:this.state.data.map不是一个函数 - React - TypeError: this.state.data.map is not a function 反应类型错误 this.state.data.map 不是 function - React TypeError this.state.data.map is not a function 尝试在 React 中从 API 获取数据 - TypeError: recipes.map is not a function - Trying to fetch data from API in React - TypeError: recipes.map is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM