【问题标题】:React: Data.map not rerendering after data state has been updated反应:数据状态更新后 Data.map 不重新渲染
【发布时间】:2022-02-08 06:24:37
【问题描述】:

我正在尝试学习如何使用 react 和 TailwindCss 对一些数据进行排序,但是在尝试时我发现了一个我无法解决的问题,在对数据数组进行排序后它不是 data.map 不是重新渲染我不知道为什么,有人可以帮助我了解如何解决它,以及为什么会发生这种情况。

import { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [data, setData] = useState([]);

  // this is the sorting function
  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
    console.log("sort",data);
  };

  useEffect(() => {
    axios
      .get("https://dummyapi.io/data/v1/user?limit=50", {
        headers: {
          "app-id": "6200ff0858dcad3e84d67c55",
        },
      })
      .then((res) => {
        setData(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    console.log(data);
  }, [data])

  return (
    <div className="flex justify-center min-h-screen App bg-background min-w-screen">
      <div className="container">
        <div className="flex flex-col items-center gap-4 py-5">
          <h1 className="text-3xl">Filter & sorting app</h1>
          <div className="relative w-full">
            <div className="right-0 ">
              <select className="flex content-end px-3 py-2 bg-white shadow-sm rounded-xl">
                <option
                  value="volvo"
                  className="text-gray-100"
                  selected
                  disabled
                  hidden
                >
                  Sort by
                </option>
                <option value="saab" onClick={sortData}>
                  Ascending
                </option>
                <option value="opel">Descending</option>
              </select>
            </div>
          </div>
          <div className="w-full flex justify-center gap-8 flex-wrap bg-white p-8 min-h-[300px] border-2 rounded-xl">
            {/* here i map on the data state but it does nor re-render after data has changed  */}
            {data?.length > 0 ? (
              data.map((user) => (
                <div
                  className="bg-blue-300 sm:w-[200px] sm:h-[200px] w-[150px] h-[150px] rounded-3xl p-4 flex flex-col items-center mt-8"
                  key={user.id}
                >
                  <img
                    src={user.picture}
                    alt={`"user_"${user.id}`}
                    className="relative w-20 h-20 rounded-full -top-12"
                  />
                  <div className="flex flex-row -mt-6 text-center sm:mt-0">
                    <h1 className="text-xl capitalize sm:text-3xl">
                      {user.title}.&nbsp;
                      <p className="text-sm sm:text-xl">
                        {user.firstName} {user.lastName}
                      </p>
                    </h1>
                  </div>
                </div>
              ))
            ) : (
              <div className="flex items-center justify-center">
                <h1 className="text-3xl">Loading...</h1>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

EDIT:如果你有更好的实现,请告诉我。

【问题讨论】:

  • 控制台res.data.data首先查看数据结构
  • 去掉return语句中的{console.log(data)},错误可能来自那里
  • @RidwanAjibola 我试过了,但这不是问题。
  • 你拿到数据了吗?
  • 我删除了它并在数据更改时尝试使用 useEffect,但点击时数据似乎没有更改。

标签: javascript reactjs tailwind-css


【解决方案1】:

此排序函数不返回任何数组。所以改为:

  const sortData = () => {
    setData(data.sort((a, b) => a.firstName.localeCompare(b.firstName)));
  };

试试这个

  const sortData = () => { 
    var newArr = [...data];
    newArr.sort((a, b) => a.firstName.localeCompare(b.firstName))
    setData(newArr);
  };

【讨论】:

  • 非常感谢您的解释,这是一个愚蠢的错误。
猜你喜欢
  • 2020-01-13
  • 2021-01-27
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
  • 2017-12-23
相关资源
最近更新 更多