简体   繁体   English

Uncaught (in promise) TypeError: res.map is not a function

[英]Uncaught (in promise) TypeError: res.map is not a function

I'm trying to fetch a list of departments from an url in a react native application我正在尝试从本机应用程序的 url 中获取部门列表

import React,{ useState,useEffect} from 'react';
import { StyleSheet, LogBox,View,Text } from 'react-native';




export default function App() {
var [department,setDepartment]=useState([])
const token = /* my token here */

  const getDepartments=()=>{  
    const url = /*my api's url here*/

      return fetch(url, {
          method: 'GET',
          headers: { "Authorization": "Bearer" + token ,
          'Accept': 'application/json',
          'Content-Type':'application/json'
      }
      })
          .then(response => response.json())
           .then(data=>console.log(data)) // returns the correct data
          .catch(error => console.error(error))
  }

   const getdepartment = async () => {
            await getDepartments().then((res) => //here lays the problem
              {res.map((p, key) => {
                department.push({
                  name: p.name,
                  id: p.id,
                });
              });
            });
          };

          useEffect(() => {

            getdepartment();

          }, []);

  return (
  <View>
  <Text>
             {department[0]}
                            </Text>

              </View>
  )
}

here res in the getdepartment() function is undefined despite the getDepartments() function returning correct data from the url尽管 getDepartments() 函数从 url 返回正确的数据,但 getdepartment() 函数中的 res 未定义

You are not returning a value from getDepartments, just a simple console.log.您不是从 getDepartments 返回值,只是一个简单的 console.log。

You can convert the function in async/await:您可以在 async/await 中转换函数:

const getDepartments = async () => {  
    const url = /*my api's url here*/
    try {
      const response = await fetch(url, {
          method: 'GET',
          headers: { "Authorization": "Bearer" + token ,
          'Accept': 'application/json',
          'Content-Type':'application/json'
      }
      })
      return await response.json();
      } catch(e){
        // error
      }
  }

or return a value from your function:或从您的函数返回一个值:

const getDepartments=()=>{  
    const url = /*my api's url here*/

      return fetch(url, {
          method: 'GET',
          headers: { "Authorization": "Bearer" + token ,
          'Accept': 'application/json',
          'Content-Type':'application/json'
      }
      })
          .then(response => response.json())
          .catch(error => console.error(error))
  }

If you are returning the result of the fetch then just return the result obtained from it, the issue is along with fetch, the response is also handled and the complete thing post to that is being returned which is not the result so you just need to skip this line .then(data=>console.log(data))如果您要返回 fetch 的结果,则只返回从中获得的结果,问题与 fetch 一起出现,响应也会被处理,并且返回的完整内容不是结果,因此您只需要跳过这一行 .then(data=>console.log(data))

const getDepartments=()=>{  
const url = /*my api's url here*/

  return fetch(url, {
      method: 'GET',
      headers: { "Authorization": "Bearer" + token ,
      'Accept': 'application/json',
      'Content-Type':'application/json'
  }
  }).then(response =>  response.json()).catch(error => 
     console.error(error))
   
  }

// Here after fetching the result you can map the data // 这里在获取结果后可以映射数据

  const getdepartment = async () => {
        await getDepartments().then((res) => 
          {res.map((p, key) => {
            department.push({
              name: p.name,
              id: p.id,
            });
          });
        });
      };

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

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