我正在使用react js建立一个锻炼网站,但我遇到了。slice()函数的问题。这是给误差练习。Slice不是来自于props
的函数import React, { useEffect, useState } from "react";
import Pagination from "@mui/material/Pagination";
import { Box, Stack, Typography } from "@mui/material";
import { exerciseOptions, fetchData } from "../utils/fetchData";
import ExerciseCard from "./ExcerciseCard";
const Exercises = ({ exercises, setExercises, bodyPart }) => {
const [currentPage, setCurrentPage] = useState(1);
const [exercisesPerPage] = useState(6);
useEffect(() => {
const fetchExercisesData = async () => {
let exercisesData = [];
if (bodyPart === "all") {
exercisesData = await fetchData(
"https://exercisedb.p.rapidapi.com/exercises",
exerciseOptions
);
} else {
exercisesData = await fetchData(
`https://exercisedb.p.rapidapi.com/exercises/bodyPart/${bodyPart}`,
exerciseOptions
);
}
setExercises(exercisesData);
};
fetchExercisesData();
}, [bodyPart]);
// Pagination
const indexOfLastExercise = currentPage * exercisesPerPage;
const indexOfFirstExercise = indexOfLastExercise - exercisesPerPage;
const currentExercises = exercises.slice(
indexOfFirstExercise,
indexOfLastExercise
)
const paginate = (event, value) => {
setCurrentPage(value);
window.scrollTo({ top: 1800, behavior: "smooth" });
};
return (
<Box id="exercises" sx={{ mt: { lg: "109px" } }} mt="50px" p="20px">
<Typography
variant="h4"
fontWeight="bold"
sx={{ fontSize: { lg: "44px", xs: "30px" } }}
mb="46px"
>
Showing Results
</Typography>
<Stack
direction="row"
sx={{ gap: { lg: "107px", xs: "50px" } }}
flexWrap="wrap"
justifyContent="center"
>
{currentExercises.map((exercise, idx) => (
<ExerciseCard key={idx} exercise={exercise} />
))}
</Stack>
<Stack sx={{ mt: { lg: "114px", xs: "70px" } }} alignItems="center">
{exercises.length > 9 && (
<Pagination
color="standard"
shape="rounded"
defaultPage={1}
count={Math.ceil(exercises.length / exercisesPerPage)}
page={currentPage}
onChange={paginate}
size="large"
/>
)}
</Stack>
</Box>
);
};
export default Exercises;
下面是练习代码。jsx文件
我尝试将其转换为toString,但它没有帮助,并给出相同的错误输入图像描述这里
像这样解构道具会导致问题。'exercises'有'any'类型,你不能在'any'上调用'.slice()'。它需要是一个数组或字符串。你需要设置"练习"的类型。
你可以这样做:
const Exercises = (props:any) => {
const exercises:string[] = props.exercises;
const currentExercises = exercises.slice(indexOfFirstExercise,indexOfLastExercise)
return (
<>
<h1>Hello</h1>
</>
);
};
或者你可以使用接口来解决这个问题。下面是一个很好的答案:使用TypeScript
解构函数参数中的props基本上,你需要遵循TypeScript规则。