收到错误“TypeError:results.map 不是函数”

在 React 代码中,当尝试映射 API 的结果时,我无法获取数据。这是供参考的代码。

  1. 应用程序.js

export const AdminPanel = () => {

  const classes = useStyles();


  const [results, setResults] = useState([])


  const profileData = async () => {

    try {

        const res = await axios.get("https://randomuser.me/api/?results=10");

        setResults(res)

    } catch(err) {

        console.log(err)

    }

}


useEffect(() => {

    profileData()

}, [])


  return (

    <TableContainer component={Paper}>

      <Table className={classes.table} aria-label="simple table">

        <TableHead>

          <TableRow>

            <TableCell>First Name</TableCell>

            <TableCell align="right">Last Name</TableCell>

            <TableCell align="right">Address</TableCell>

            <TableCell align="right">Photo</TableCell>

            <TableCell align="right">Email</TableCell>

            <TableCell align="right">DOB</TableCell>

          </TableRow>

        </TableHead>

        <TableBody>


            {results.map((person) => {

                console.log('PERSON', person)

            })}


        </TableBody>

      </Table>

    </TableContainer>

  );

}

即使将结果声明为数组,仍然会出现错误。我是否在某个地方弄错了。什么是合适的解决方案?


回首忆惘然
浏览 118回答 2
2回答

子衿沉夜

你快到了。您的 axios 调用需要稍微改变一下。以下是修复方法:import React from "react";import axios from "axios";import "./styles.css";export default function App() {&nbsp; const [results, setResults] = React.useState([]);&nbsp; const profileData = async () => {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; const res = await axios&nbsp; &nbsp; &nbsp; &nbsp; .get("https://randomuser.me/api/?results=10")&nbsp; &nbsp; &nbsp; &nbsp; .then((result) => result.data.results);&nbsp; &nbsp; &nbsp; setResults(res)&nbsp; &nbsp; } catch (err) {&nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; }&nbsp; };&nbsp; React.useEffect(() => {&nbsp; &nbsp; profileData();&nbsp; }, []);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <h1>Hello CodeSandbox</h1>&nbsp; &nbsp; &nbsp; <h2>Start editing to see some magic happen!</h2>&nbsp; &nbsp; &nbsp; {results.map((person) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log("PERSON", person);&nbsp; &nbsp; &nbsp; })}&nbsp; &nbsp; </div>&nbsp; );}注意这部分:const res = await axios&nbsp; &nbsp; &nbsp; &nbsp; .get("https://randomuser.me/api/?results=10")&nbsp; &nbsp; &nbsp; &nbsp; .then((result) => result.data.results);另请记住,console.log("PERSON", person);在返回函数内部实际上不会在页面上呈现任何内容,它将打印到控制台。只是想澄清这一点。沙盒:https://codesandbox.io/s/exciting-shockley-9m5vj? file=/src/App.js

慕容708150

setResults(res.results) 应该完成这项工作
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript