javascript - 基于函数返回的条件类名
问题描述
在我的 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 之间更改类名fas
并far
基于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;
解决方案
这里的问题在于您的函数,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)
}
推荐阅读
- sql - 为 group by 中的每个组创建列
- ontology - 如何在 WebProtege 4.0 中列出用户?
- python - 使用 pipenv 安装枕头时出现 Pipfile.Lock 问题
- c# - C# - 静态数组的有效初始化,其中每个元素都是函数的输出
- reactjs - 多个放置目标 react-dropzone
- python - FileNotFoundError:“pyannote.database”
- python - MVC模型中的PyQt5信号和插槽不起作用
- c# - 获取 Azure AD 访问令牌到期日期的正确方法
- wildfly - 无法获取 JDBC 连接 Keycloak 服务器
- hadoop - 如何在 hive select 之外使用 IF else 语句?