嗨,我做了一个项目并以三种方式排序:日期,标题,编号,但即使没有任何错误通知,所有这些都不起作用。所以我不知道如何进入窃听过程。请帮助我,谢谢。
import ColorCards from "./ColorCards";
import React, { useState } from "react";
import data from "./initialState.json";
import { v4 as uuidv4 } from "uuid";
export default function CardsafterEvents({ title, color }) {
const [colors, setColors] = useState(data.colors);
const onRemove = (id) => {
const newcolors = colors.filter((color) => color.id !== id);
setColors(newcolors);
};
const AddColor = (title, color, timestamp) => {
const newcolors = [
...colors,
{
id: uuidv4(),
title: title,
color: color,
timestamp: timestamp
}
];
setColors(newcolors);
};
const SortbyDate = () => {
const newcolors = colors.sort(
(a, b) => new Date(b.date) - new Date(a.date)
);
setColors(newcolors);
};
const SortbyTitle = () => {
const newcolors = colors.sort((a, b) =>
a.title > b.title ? 1 : b.title > a.title ? -1 : 0
);
setColors(newcolors);
};
const SortbyRating = () => {
const newcolors = colors.sort((a, b) => a.rating - b.rating);
setColors(newcolors);
};
return (
<>
<ColorCards
dataColors={colors}
handleDelete={onRemove}
HandleColor={AddColor}
onDate={SortbyDate}
onTitle={SortbyTitle}
onRating={SortbyRating}
/>
</>
);
}
完整的项目链接:https://codesandbox.io/s/material-demo-forked-62eh0?file=/CardsafterEvents.js:0-1330
答案 0 :(得分:0)
函数在调用它们的上下文中无权访问您的 colors
和 setColors
。您需要将它们作为参数发送给他们的孩子,例如:
const SortbyDate = (colors, setColors) => {
const newcolors = colors.sort(
(a, b) => new Date(b.date) - new Date(a.date)
);
setColors(newcolors);
};
然后:
<ColorCards
...
onDate={() => SortbyDate(colors, setColors)}
...
/>
OR 将 colors
和 setColors
作为它们自己的 props 发送下来,然后在调用函数时使用它们,例如:
<ColorCards
...
colors={colors}
setColors={setColors}
onDate={SortbyDate}
...
/>
在子组件中:
props.onDate(props.colors, props.setColors)
答案 1 :(得分:0)
如果不是因为您的 Sort 函数正在改变状态变量,您的代码本来可以工作的。是的,sort
会改变原始数组,因此:
const newcolors = colors.sort((a, b) =>
a.title > b.title ? 1 : b.title > a.title ? -1 : 0
);
实际上改变了你的 colors
状态变量。当然,这在 React 中是不可以的。我将向您展示如何使您的 SortbyTitle
函数工作,您也可以对其他 Sort 函数执行相同的操作。您需要创建 sate 变量的副本,然后才在其上使用 sort
。试试这个:
const SortbyTitle = () => {
const copy_of_ar = JSON.parse(JSON.stringify(colors));
copy_of_ar.sort((a, b) =>
a.title > b.title ? 1 : b.title > a.title ? -1 : 0
);
setColors(copy_of_ar);
};
这里有一个 Sandbox 为您准备了一个有效的标题分类器。