我在React中添加到收藏夹函数。多亏了每个人的帮助,我才能以某种方式完成这项工作,除了喜欢和不喜欢之间切换。我被编码为“ likes: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>
)
}
}
答案 0 :(得分:2)
正确的条件是
if (!(this.state.likes.filter(e => e.name === person.name).length > 0)) {
// your code
}
条件的含义是:
this.state.likes.filter(e => e.name === person.name)。长度> 0) 仅当数组中的元素与提供的 person 对象 name 匹配时,才会过滤出数组。指出 person 已存在于数组中
!用于检查相反的情况,因为您只想在不存在人员的情况下输入 if 语句
编辑 为了更好地阅读代码,可以使用更简单,更简洁的方法来实现:
addPerson = (person) => {
let filteredPerson = this.state.likes.filter(like => like.name !== person.name);
this.setState({
likes: [...filteredPerson, person]
})
}
查看以下工作片段: https://stackblitz.com/edit/react-jxebwg
答案 1 :(得分:0)
您可以通过两种不同的方法来解决这个问题。
使用.includes()
handleClick = person => {
const likes = this.state.likes
//check to see if person has already liked
if (likes.includes(person)) {
//user has already liked. Choose one option (1 or 2)
//Option 1: create a new like array without the current user
const newLikes = likes.filter((like) => like !== person)
//Option 1: update state with new likes
this.setState({
likes: newLikes
})
//Option 2: or do nothing
return;
//this executes if the user has not liked yet
} else {
this.setState({
likes: [...likes, person]
})
}
};
因此,“执行以下一项操作”的意思取决于您希望功能的行为方式。
选项1: 如果要创建某种切换效果,则用户已经喜欢该项目。您应该选择一个选项,在该选项中我们创建一个新的arr并更新状态。这将“不喜欢”,将用户从喜欢的数组中删除。然后点击
选项2: 只会无所事事。如果用户单击该按钮并且他们已经喜欢它,那么状态将保持不变。