javascript - 无法过滤数组以在 react 应用程序上获取电影

标签 javascript reactjs

我有一个名为 handleDelete 的函数,它接受一个 movie 对象,并将根据传递的 movie 进行过滤。当我单击它时,出现错误 Cannot read property 'filter' of undefined

更新:发布所有代码。

JS

handleDelete = (movie) => {
    const movies = this.setState.movies.filter(m => m._id !== movie._id);
    this.setState({ movies });
};

JSX

import React, { Component } from "react";
import "../services/fakeMovieService";
import { getMovies } from "../services/fakeMovieService";

class MovieTable extends Component {
   state = {
   movies: getMovies()
};

render() {
   return (<table className="table">
    <thead>
      <tr>
        <th scope="col">Title</th>
        <th scope="col">Genre</th>
        <th scope="col">Stock</th>
        <th scope="col">Rate</th>
        <th> </th>
      </tr>
    </thead>
    <tbody>
      {this.state.movies.map(movies => (
        <tr key={movies._id}>
          <td> {movies.title} </td>
          <td> {movies.genre.name}</td>
          <td> {movies.numberInStock} </td>
          <td> {movies.dailyRentalRate}</td>
          <td
            onClick={movie => this.handleDelete(movie)}
            className="btn btn-danger btn-sm"
          >
            Delete
          </td>
        </tr>
      ))}
    </tbody>
  </table>);
}}

 export default MovieTable;

电影数组

const movies = [ {
    _id: "5b21ca3eeb7f6fbccd471815",
    title: "Terminator",
    genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
    numberInStock: 6,
    dailyRentalRate: 2.5,
    publishDate: "2018-01-03T19:04:28.809Z"
}];

最佳答案

看起来你打错了 this.setState.movi​​es.filter 应该是 this.state.movi​​es.filter 所以:

handleDelete = movie => {
    const movies = this.state.movies.filter(m => m._id !== movie._id);
    this.setState({ movies });
};

关于javascript - 无法过滤数组以在 react 应用程序上获取电影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52122885/

相关文章:

css - 如何在悬停在封闭的 div 容器上时更改图标颜色

javascript - 在给定时间范围内显示不同的图像

javascript - 在 webpack React 中使用图像不起作用

javascript - 在 React 中使用 Buttons 触发 react-table 上的过滤功能

javascript - 使用现代 CSS 过渡使文本立即出现但逐渐淡出

javascript - 如何使用 JavaScript 查看已打开的广播 channel ?

javascript - angularjs 从属性文件中读取

javascript - React Hooks Clock - 在特定时间后清除 SetInterval

javascript - 检查元素的祖先是否固定

javascript - Laravel + React : Pass Function in JSON response