【问题标题】:React does not show all value of an array returned from axiosReact 不显示从 axios 返回的数组的所有值
【发布时间】:2021-03-17 06:35:51
【问题描述】:

这是我的后端NodeJS 代码:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const cors = require('cors');

app.get('/getEmployees', cors(), (req, res) => {
    res.send([
        '00001 | Alice',
        '00002 | Bob',
        '00003 | Charlie',
        '00004 | Dave',
        '00005 | Eve',
        '00006 | Frank',
    ]);
});

app.listen(port, () => {
    console.log(`Server is up on port ${port}`);
});

这是我的前端 React 代码:

import React, { useState, useEffect } from 'react';
import classes from './App.module.css';
import axios from 'axios';

function App() {

    const [employeesList, setEmployeesList] = useState(null);

    useEffect(() => {
        axios.get('http://127.0.0.1:3000/getEmployees').then((response) => {
            console.log(response.data); // Checking value
            let list = [];
            response.data.map((employee) => {
                list.push(<option>{employee}</option>)
                return setEmployeesList(list)
            })
        });
    }, []);

    return (
        <div className={classes.App}>
            Please select employee:
            <select>
                {employeesList}
            </select>
        </div>
    );
};

export default App;

当我运行它们时,我可以在浏览器上看到一个下拉列表,但只有一个值,即第一个员工 Alice。

如您所见,我在 axios 函数中执行 console.log 并打印多个员工。我希望在下拉列表中看到所有员工。谁能帮帮我?

【问题讨论】:

  • 你做错了一堆事情。我会推荐console.log(employeesList) 之前return 的App 功能。这应该会为您解决问题。

标签: node.js reactjs axios setstate use-effect


【解决方案1】:

如下更改您的useEffect

  useEffect(() => {
    axios.get('http://127.0.0.1:3000/getEmployees').then((response) => {
      response.data.map((employee, index) => {
        list.push(<option key={index.toString()}>{employee}</option>)
      })
      setEmployeesList(list);
    });
  }, []);

Codesandbox Here

【讨论】:

  • 这行得通!。只需将setEmployeeList(list) 移动到地图功能之外。感谢您的帮助。
【解决方案2】:

问题在于 map 函数回调内部,在这种情况下它返回一个 2D 元素数组,我建议将原始数据设置为 state,然后在 jsx 中使用 map 来呈现项目:

function App() {

    const [employeesList, setEmployeesList] = useState([]);//init the state as an empty array

    useEffect(() => {
        axios.get('http://127.0.0.1:3000/getEmployees').then((response) => {
            console.log(response.data); // Checking value
                 setEmployeesList(response.data)
            
        });
    }, []);

    return (
        <div className={classes.App}>
            Please select employee:
            <select>
                {employeesList.map((emp,index)=>{
                  
                   return <option key={index} value={emp}>{emp}</option>

                 }}
            </select>
        </div>
    );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2019-08-11
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多