【问题标题】:Uncaught (in promise) TypeError: res.map is not a functionUncaught (in promise) TypeError: res.map is not a function
【发布时间】:2021-09-30 16:30:06
【问题描述】:

我正在尝试从 react 本机应用程序中的 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>
  )
}

尽管 getDepartments() 函数从 url 返回正确的数据,但 getdepartment() 函数中的 res 是未定义的

【问题讨论】:

  • 如果要使用.then,则不需要使用await,只需使用const response = await getDepartments();,然后对响应变量执行所有逻辑,所以response.map ...
  • 去掉.then(data=&gt;console.log(data))或者改成.then(data=&gt;{ console.log(data); return data; })
  • @ponury-kostek 我都试过了..还是不行
  • 你确定res 是一个数组吗?对象上不存在地图
  • 我认为@skrrrt 和@ponury 的评论应该可以帮助您找出问题所在。首先,检查数据实际上是一个数组。其次,确保通过.then(data=&gt;{ console.log(data); return data; }) 返回您的promise 中的数据(注意大括号是必需的)。通过console.log 但不返回任何内容,您没有从该承诺链中获得任何价值(因此undefined

标签: javascript reactjs react-native frontend


【解决方案1】:

您没有从 getDepartments 返回值,只是一个简单的 console.log。

你可以在 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
      }
  }

或者从你的函数中返回一个值:

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))
  }

【讨论】:

    【解决方案2】:

    如果您要返回 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))
       
      }
    

    //这里获取结果后可以映射数据

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

    【讨论】: