我又问了一个问题。但我得到的都是没用的答案。我实际上没有得到正确的解。
这里我使用redux从后端得到一个数组。
const { movies, message } = useAppSelector(state => state.movies);
在state.movies
中有两个字段的对象。一个是movies
,另一个是message
。我在创建redux reducer时定义了类型。在分量1中得到这个。movies
类型是array
(实际上我是通过这个电影字段从后端得到一个数组)。message
类型为string
。
一句话。这里movies
是数组,message
是字符串。我在state.movies
上发现了这两个字段。
现在我要过滤movies
-
const mathches = movies.filter((movie: movie ) => {
const escapeRegExp = (str: string) => str.replace(/[-[]/{}()*+?.\^$|]/g, "\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
但这里我得到一个错误,如-Property 'filter' does not exist on type 'never'
.
movies
字段是数组。但我怎么能告诉或定义它。
这是完整的组件-
import type { NextPage } from "next";
import { useState, useEffect } from "react";
import { Container } from "@mui/material";
import { GetServerSideProps } from "next";
//Redux
import { wrapper } from "Redux/Store";
import { getMovies } from "Redux/Action/movieAction";
import { useAppSelector } from "Redux/Hook";
//Components
import Search from "Components/Movies/Search";
import Lists from "Components/Movies/Lists";
type movie = {
name: string;
image: string;
releaseDate: string;
watchedDate: string;
}
const Movies: NextPage = () => {
const { movies, message } = useAppSelector(state => state.movies);
const [movieList, setMovieList] = useState<[]>(movies);
const [search, setSearch] = useState<string>("");
useEffect(() => {
let mathches = []
if (search.length > 0) {
mathches = movies.filter((movie: movie ) => {
const escapeRegExp = (str: string) => str.replace(/[-[]/{}()*+?.\^$|]/g, "\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
}
setMovieList(mathches);
}, [search, movies])
return (
<Container maxWidth={false} disableGutters>
<Search setSearch={setSearch} />
<Lists movies={movieList} />
</Container>
);
};
export default Movies;
我看到了两个问题。
- 你的状态定义有错误的泛型类型
- useAppSelector返回
never
类型
第一个问题的解决方案是用合适的类型定义movieList
状态,如下所示:
const [movieList, setMovieList] = useState<movie[]>(movies);
对于第二个问题,请检查您是否正确定义了redux-toolkit类型,请参阅此处的文档:https://redux-toolkit.js.org/tutorials/typescript#define-root-state-and-dispatch-types
如果以上方法都失败,可以将钩子返回类型强制转换为自定义类型,如下所示:
type MovieReducer = {
movies: movies[];
message: string; // check if this is the correct type
}
const { movies, message } = useAppSelector((state) => state.movies) as unknown as MovieReducer;