TypeError: allOrg.map is not a function

TypeError: allOrg.map is not a function

我试图在反应中循环遍历数组状态中的所有对象,因此我使用了 map 函数。这是我使用 map 函数的代码块:

return(
<div>
         <Navbar/><br/>
         {
            allOrg.map((data: orgType, index: number) => {
               /*<Org key={index} userId = {UserId} orgName = {data.orgName} /> */
               <h1>{index}  {UserId}  {data.orgName}</h1>
            })
         }
         <div className = "OrgRow">
            <button className = "OrgTeams" onClick={createOrg}>Add Org</button>
            {createOrgForm}
         </div>
      </div>
   )  

但它向我显示“TypeError:allOrg.map 不是函数”错误。 picture of the error 我在 Whosebug 上查找了类似的错误,但唯一的建议是 map 只能与数组一起使用。这里我的状态只是一个数组,这个问题仍然存在。这是我对名为“allOrg”的状态的声明:

import React,{useState, useEffect} from "react";
import { useForm } from "react-hook-form";
import Navbar from "./navBar";
import Org from "./org";
import "../../style/auth.css";
import "../../style/home.css";

interface orgType{
   orgId: string;
   orgName: string;
}

function Home(): JSX.Element{

   //let UserId: string = "Ronak";
   const initialOrg = {
      orgId: "",
      orgName: ""
   }
   const [UserId, setUserId] = useState<string>("userId");
   const [createOrgForm, setForm] = useState(<div></div>);
   const [allOrg, setAllOrg] = useState<orgType[]>([initialOrg]);
   const [orgAdded, changeState] = useState(true);
   const {register, handleSubmit} = useForm();

我还粘贴了包含该组件的完整代码的图像:

import React,{useState, useEffect} from "react";
import { useForm } from "react-hook-form";
import Navbar from "./navBar";
import Org from "./org";
import "../../style/auth.css";
import "../../style/home.css";

interface orgType{
   orgId: string;
   orgName: string;
}

function Home(): JSX.Element{

   //let UserId: string = "Ronak";
   const initialOrg = {
      orgId: "",
      orgName: ""
   }
   const [UserId, setUserId] = useState<string>("userId");
   const [createOrgForm, setForm] = useState(<div></div>);
   const [allOrg, setAllOrg] = useState<orgType[]>([initialOrg]);
   const [orgAdded, changeState] = useState(true);
   const {register, handleSubmit} = useForm();

   const submitButton = {      
      margin: "auto",
      marginTop: 30,
      display: "block"
   }

   useEffect(() => {
      fetch('/api/v1/auth/verifyJWT', {
         method: 'POST',
         headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
         },
      })
      .then(res => res.json())
      .then(data => {
               console.log(data.serviceResponse.userId);
               setUserId(data.serviceResponse.userId);
               console.log(UserId);
            }
      )
   }, [] )

   useEffect( () => {
      console.log(UserId);
      fetch('/api/v1/org/all/' + UserId)
      .then(res => res.json())
      .then(data => {
            setAllOrg(data);
            console.log("Hi");
            console.log(data);
            console.log(allOrg);
            console.log("bye");
         }
      )}, [UserId]);
   
   function onSubmit(data: any){
      fetch('/api/v1/org/create', {
         method: 'POST',
         headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
         },
         body: JSON.stringify(data)
      })
      .then(res => res.json())
      .then(data => {
         console.log(data);
         if(data.message == "Created!"){
            console.log("successful");
            setForm(()=><div></div>);
            changeState(!orgAdded);
         }
         else{
            console.log("failed");
         }
      })
   }

   function createOrg(){
      console.log(UserId);
      setForm(()=>
         <form className = "auth_form" onSubmit = {handleSubmit(onSubmit)}>
            <br/><br/>
            <input className = "auth_input" {...register("userId", {required: true})} name="userId"  value={UserId}/>
            <br/>
            <input className = "auth_input" {...register("orgName", {required: true})} name="orgName" placeholder="Organization Name"/>
            <br/>
            <button className = "auth_button" style={submitButton} type="submit">Create</button> 
         </form>
      )
   }
   
   return(
      <div>
         <Navbar/><br/>
         {
            allOrg.map((data: orgType, index: number) => {
               /*<Org key={index} userId = {UserId} orgName = {data.orgName} /> */
               <h1>{index}  {UserId}  {data.orgName}</h1>
            })
         }
         <div className = "OrgRow">
            <button className = "OrgTeams" onClick={createOrg}>Add Org</button>
            {createOrgForm}
         </div>
      </div>
   )
}

export default Home;

第 103 行是我使用 allOrg.map() 的地方,allOrg 状态的声明在函数的开头。

欢迎任何帮助。 P.S。如果有人认为 allOrg 状态可能为空,则事实并非如此。我使用 console.log..

检查

编辑:我正在添加 allOrg console.log 的 ss,console.log(allOrg)。

即使您检查过 allOrg 的状态不为空,组件也可能被渲染多次,其中第一次 allOrg 处于初始状态以进行第二次渲染时,它可能为空、null 或未定义,最后当 API调用完成它填充allOrg.

所以你必须处理 allOrg 为 null 或其他情况的情况。

let orgList;
if(Array.isArray(allOrg)){
    orgList = allOrg.map(
        ...
    );
}
render (
    ...
    {orgList}
    ...
);