简体   繁体   中英

“TypeError: kinds.map is not a function.” React.js

I'm trying to get data from an API and return it as a 'state' inside a component which is Navbar component but when i try to loop inside the data i get from the API, using 'map' i get an following error

"TypeError: kinds.map is not a function."

I can console.log the data which is following but can't display in my component this is the data i get from my browser console:

 [["1", "Electronic"], ["2", "Clothes"], ["3", "Beauty"], ["4", "Phone Cases"]]

My only component is following:

function getProductKinds(callBack) {
  var url = "http://localhost:8000/api/products";
  const responseType = 'json';
  const method = "GET";
  const xhr = new XMLHttpRequest();

  xhr.open(method, url);

  xhr.onload = () => {
    //console.log(xhr.response, xhr.status);
    callBack(xhr.response, xhr.status);
  };

  xhr.send();
}

function NavbarComponent(props) {
  const [kinds, setKinds] = useState([]);
  useEffect(() => {
    const myCallBack = (response, status) => {
      console.log("received data: ", response, status);
      if (status === 200) {
        setKinds(response);
        console.log("received data2: ", kinds, status);
      }
    };
    getProductKinds(myCallBack);
  }, []);
  return (
    <div>
      <Navbar color="light" light expand="md">
        <NavbarBrand href="/">BRAND</NavbarBrand>
        <Nav className="mx-auto " navbar>
        {kinds.map((kind) => {
            <NavItem>ss</NavItem>;
          })}
        </Nav>
        <NavbarText>Simple Text</NavbarText>
      </Navbar>
    </div>
  );
}

export default NavbarComponent;

and the function App is following code:

import './App.css';
import React from 'react';

import { useEffect } from 'react';
import NavbarComponent from './components/navbar';

function App() {

  return (
        <NavbarComponent></NavbarComponent>
  );
}

export default App;

我的浏览器上的字符串输出的屏幕截图

First try to use JSON.parse(response).map to convert that 2D array to array of objects then return the NavItem inside the map callback:

setKinds(JSON.parse(response).map((curr)=>{
    return {id:curr[0],name:curr[1]}
}))

and

{kinds.map((kind,index)=>{

   return <NavItem key={index}>{kind.name}</NavItem>
}

When you fetch data from API, it takes a little bit of time. But react is not waiting for that process to finish and maybe your kinds array is empty when react is rendering. You should try this. Instead of

{kinds.map((kind) => {
  <NavItem>ss</NavItem>;
})}

try this..

{kinds && kinds.map((kind) => {
  <NavItem>ss</NavItem>;
})}

this should work

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