首页 > 解决方案 > 基于函数返回的条件类名

问题描述

在我的 React 项目中,我试图根据每个项目在我从本地存储中获取的数组中的存在情况为每个项目设置不同的图标。

表.js

import React from 'react';
import isMovieInFavorites from './favorites';

class Table extends React.Component {
  constructor(props){
    super(props);
    this.state = {
        movies: [],
        //other state vars
    }
  }

  //some other codes
  render(){
      return (
        <div className="table-container">
          <table>
            {this.state.movies.map((row) => (
              <tr key={row.id}>
                <td>{row.title}</td>
                <td className="icon"><i className={(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}></i></td>
              </tr>
            ))}
          </table>
        </div>
      );
  }
}

我正在尝试在 from 之间更改类名fasfar基于isMovieInFavorites(id)from

收藏夹.js

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  movieArray.forEach((movie)=>{
    if(movie.id === id)
      return true;
  });
  return false;
}

我想我在这部分做得很好:

{(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}

console.log如果我检查(内部favorites.js)中的结果,因为条件很好。此外,如果我做类似的事情{(row.id == 10 ? "fas" : "far") + " fa-star"},它工作正常。但是调用该函数并以某种方式检查结果是行不通的,far即使结果是true.

我在这里想念什么?在这种情况下调用函数是错误的吗?

导出默认 isMovieInFavorites;

标签: javascriptreactjs

解决方案


这里的问题在于您的函数,forEach 不会从回调中返回任何内容,因此该函数将始终返回false

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  movieArray.forEach((movie)=>{
    if(movie.id === id)
      return true;
  });
  return false;
}

您需要使用some或简单for循环

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  return movieArray.some(movie => movie.id === id)
}

推荐阅读