首页 > 解决方案 > 映射数据的问题 - React

问题描述

你知道为什么我不能通过待办事项进行映射吗?我在网上关注教程,我和其他人完全一样,但它没有通过数据映射。我得到了 json,我可以在客户端控制台中看到待办事项。

import React, { Fragment, useEffect, useState } from "react";

const ListTodos = () => {
  const [todos, setTodos] = useState([]);

  const getTodos = async () => {
    try {
      const response = await fetch("http://localhost:5000/todos");
      const jsonData = await response.json();

      setTodos(jsonData);
    } catch (err) {
      console.error(err.message);
    }
  };

  useEffect(() => {
    getTodos();
  }, []);

return (
    <Fragment>
      <table className="table mt-5 text-center">
        <thead>
          <tr>
            <th>Description</th>
            <th>Edit</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
        
          {todos.map((todo) => {
            <tr>
              <td>{todo.description}</td>
              <td>Edit</td>
              <td>Delete</td>
            </tr>;
          })}
        </tbody>
      </table>
    </Fragment>
  );
};

谢谢

标签: reactjspostgresqlexpress

解决方案


如果你在函数中使用花括号,你应该返回 JSX。像这样

{todos.map((todo) => {
       return (<tr>
          <td>{todo.description}</td>
          <td>Edit</td>
          <td>Delete</td>
        </tr>;
      )})}

否则用括号直接返回, Like This

{todos.map((todo) => (<tr>
          <td>{todo.description}</td>
          <td>Edit</td>
          <td>Delete</td>
        </tr> 
       ))}

推荐阅读