【发布时间】:2019-10-21 17:37:21
【问题描述】:
我正在 React 中制作添加到收藏夹功能。感谢大家的帮助,除了切换喜欢和不喜欢之外,我可以以某种方式完成这项工作。我像“喜欢:this.state.likes.filter(e => e.name !== person.name)”这样编码只是因为有人建议我这样编码。老实说,我不明白上面的代码可能是因为它是 ES6 语法。它在 ES5 中是什么样子的?现在代码不起作用,元素没有正确添加到数组中。如何修复此代码?
import React from 'react';
import axios from 'axios';
import IcoMoon from 'react-icomoon';
export default class PersonList extends React.Component {
state = {
persons: [],
likes: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
handleClick = person => {
if (this.state.likes.filter(e => e.name === person.name).length > 0) {
this.setState({
likes: this.state.likes.filter(e => e.name !== person.name)
});
console.log(this.state.likes);
return;
}
this.setState({
likes: [...this.state.likes, person]
});
};
likesTemplate = item => <li key={item}>{item}</li>;
renderLikes = () => {
return this.state.likes.map(i => this.likesTemplate(i));
}
render() {
return (
<div>
{this.state.persons.map(person => {
return <li key={person.name}><IcoMoon icon="heart" onClick={() => {this.handleClick(person.name)}} />{person.name}</li>}
)}
<h2>Favorite Person</h2>
<ul>
{this.renderLikes()}
</ul>
</div>
)
}
}
【问题讨论】:
-
您是否尝试过使用 Array.prototype.includes() 检查数组中是否存在元素。见这里:developer.mozilla.org/it/docs/Web/JavaScript/Reference/…
-
使用 Set 而不是数组也是一个好主意。毕竟,避免重复是集合的本质。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
我试过了,效果很好! “如果(this.state.likes.includes(person)){”。现在我的问题是我不知道如何删除数组中的重复元素。我正在尝试像“this.setState({ likes: this.state.likes.splice(person) });”但它不会工作:(
-
试试 this.state.likes.splice(this.state.likes.indexOf(person), 1)
-
尝试了上面的代码,但似乎我把一切都搞砸了。如果我第一次点击数组仍然是空的,如果我点击另一个人,那么前一个人就会被添加到数组中。