[你好,我正在用Typescript在React中做一个应用程序,比较两个状态(基本上是2个对象数组并进行过滤,因此我只取回allBooks
数组中包含的那些状态)时遇到问题。接口:
export interface IBook {
book_id: number;
book_name: string;
release_year: number;
}
然后是我的班级状态:
class Home extends Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
users: [],
userBooks: [],
allBooks: []
};
}
然后是比较功能:
filterBooks = () => {
const { allBooks, userBooks } = this.state;
let notUserBooks = allBooks.filter(
({ book_id }: { book_id: number }) => !userBooks.includes({book_id}));
console.log(notUserBooks, allBooks);
};`
我不知道我在做什么错,但是console.log在notUserBooks中得到的结果与在allBooks中得到的结果相同,我的意思是allBooks中包含3个项目,在控制台日志中,过滤器之后的内容为3项目....这是控制台输出:
(3) [{…}, {…}, {…}]
0: {book_name: "the lord of the rings", release_year: 1950}
1: {book_name: "the butterfly", release_year: 1980}
2: {book_name: "the hobbit", release_year: 1960}
length: 3
__proto__: Array(0)
(3) [{…}, {…}, {…}]
0: {book_name: "the lord of the rings", release_year: 1950}
1: {book_name: "the butterfly", release_year: 1980}
2: {book_name: "the hobbit", release_year: 1960}
length: 3
__proto__: Array(0)```
filterBooks = () => {
const { allBooks, userBooks } = this.state;
let notUserBooks = allBooks.filter(
({ book_id }: { book_id: number }) => !userBooks.includes({book_id}));
console.log(notUserBooks);
};
对此:
filterBooks = () => { const { allBooks, userBooks } = this.state; let notUserBooks = allBooks.filter( ({ book_id }: { book_id: number }) => !userBooks.map(book => book.book_id).includes(book_id)); console.log(notUserBooks); };
通常,您无法在javascript中比较对象。一个简单的测试:const a = { test: 'test' }; const b = { test: 'test' }; alert(a === b);