Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Typescript对React useffect()中的数组进行排序_Javascript_Arrays_Reactjs_Typescript - Fatal编程技术网

Javascript 使用Typescript对React useffect()中的数组进行排序

Javascript 使用Typescript对React useffect()中的数组进行排序,javascript,arrays,reactjs,typescript,Javascript,Arrays,Reactjs,Typescript,我正在设置useEffect中的电影对象数组,并希望它们按字母顺序排序。如果以后可能的话,我想添加按不同属性对它们进行排序的功能,但现在我只想克服这个类型脚本的难题。我有一个单独的类型文件,用于导出我的电影界面: export interface Movie { comments: string, imdb: string, mtc: string, rtc: string, smn: string, title: string } 然后我将其导

我正在设置useEffect中的电影对象数组,并希望它们按字母顺序排序。如果以后可能的话,我想添加按不同属性对它们进行排序的功能,但现在我只想克服这个类型脚本的难题。我有一个单独的类型文件,用于导出我的电影界面:

export interface Movie {
    comments: string,
    imdb: string,
    mtc: string,
    rtc: string,
    smn: string,
    title: string
}
然后我将其导入到我的页面中

import { Movie } from '../types';
我调用useEffect,从我的MongoDB请求电影列表,然后对它们进行排序

const Database = () => {

  const [movies, setMovies] = React.useState<Movie[]>([]);
  const [sortType, setSortType] = React.useState('title');
  const history = useHistory();

  React.useEffect(() => {
    Requests.getMovies()
      .then(setMovies)
      .catch (err => console.log(err));

      const types: Movie = {
        title: 'title',
        rtc: 'rtc',
        imdb: 'imdb',
        smn: 'smn',
        mtc: 'mtc',
        comments: 'comments'
      };


      const sortArray = (sortProperty: string): sortProperty is keyof typeof types => {

      const sorted = [...movies].sort((a: Movie, b: Movie) => b[sortProperty] - a[sortProperty] );

return sorted;

      }

      sortArray(sortType);
      setMovies(sortArray);
  }, [sortType])

return (
// Bunch of stuff on the page and then map out the movies like so..

      <tbody>
        {movies.map((movie, index) => (
          <tr key={index} onClick={() => history.push(`/edit/${movie.title}`)}>
            <td>{movie.title}</td>
            <td>{movie.imdb}</td>
            <td>{movie.rtc}</td>
            <td>{movie.mtc}</td>
            <td>{movie.smn}</td>
            <td>{movie.comments}</td>
          </tr>
        ))}
      </tbody>

//Bunch of other stuff on the page..
)
}

export default Database;
…在
b[sortProperty]
a[sortProperty]

Element implicitly has an 'any' type because expression of type 'string | number | symbol' can't be used to index type 'Movie'.

No index signature with a parameter of type 'string' was found on type 'Movie'.

我怎样才能让它工作?我以为sort返回的是排序数组,但它返回的是布尔值?为什么它不能按对象和接口中定义的属性进行排序?

好了,我们开始吧,我会尽可能地解释一切

首先,您需要将
useffect
拆分为两条useffect语句<代码>使用效果钩子只能处理一件事

因此,您的代码如下所示:

React.useffect(()=>{
请求。getMovies()
.然后(电影集)
.catch(err=>console.log(err));
), []}
React.useffect(()=>{
//你的分类码
},[/*依赖项*/])
这背后的原因是,您不希望对依赖项的每次更改都触发不必要的操作,也就是说,您不希望在依赖项每次更改时提取,而只希望在安装组件时提取

至于代码的问题,这些错误有两个原因:

  • 正在尝试对字符串类型的2个变量执行算术运算
  • 当对象没有泛型键时,尝试使用字符串类型的变量读取对象的属性
另外,通过
useffect
hook执行更改操作并不是最理想的解决方案,因为您需要依赖项中的
movies
状态,以便获得最新状态,但如果这样做,将触发无限循环

我这样做的方式是,在组件装载时使用获取的数组进行一次排序,然后使用事件处理程序函数触发后续排序。这样可以避免任何意外的副作用

因此,您的代码如下所示:

const[movies,setMovies]=React.useState([]);
const[sortType,setSortType]=React.useState(“title”);
React.useffect(()=>{
请求。getMovies()
.然后(sortMovies)
.catch(err=>console.log(err));
), []}
const sortMovies=(moviesParam:Movie[]=movies)=>{
const sortArray=[…moviesParam].sort((a:Movie,b:Movie)=>{
如果(a[sortType]>b[sortType])返回1;
else if(b[sortType]>a[sortType])返回-1;
返回0;
});
setMovies(Sortaray);
}
此代码按字母顺序对数组进行排序,并且不会导致无限循环

另外,
sortArray
函数实际上并不需要,因为您实际上使用了状态,因此它不会向代码添加任何值


如果您需要进一步解释我如何以及为什么做了这些更改,请添加评论,我将更新帖子。

您的代码有很多问题。我正在研究一个解决方案,一旦我完成了,我会在回复帖子中澄清所有问题。嗨,非常感谢你的帮助。我完全理解你的推理,代码确实非常清晰,但TypeScript错误仍然存在。它仍然突出显示[sortType]并告诉我两件事:1<代码>元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型为“Movie”。在“a”和“b”上。2. <代码>在类型“Movie”上找不到具有“string”类型参数的索引签名。在“sortType”上。我们似乎没有为TS定义对象的键。我自己查看它,但请回复以了解我们的方向。我实际上是在typescript环境中测试的,它没有给我问题。您确定更改了此行
const[sortType,setSortType]=React.useState(“title”)?哦,我好像忘了那个!正如你们可能已经注意到的,我对打字脚本还是有点陌生。为什么我们要在useState钩子中声明keyof?这是否会导致我们使用字符串作为键,因为我们的初始状态是字符串“title”?我们没有声明,我们将其设置为状态的类型,这样,只有具有相同值的字符串才会在我们的状态中被接受。还可以请确认我的答案,以便此答案显示为已解析。
Element implicitly has an 'any' type because expression of type 'string | number | symbol' can't be used to index type 'Movie'.

No index signature with a parameter of type 'string' was found on type 'Movie'.