繁体   English   中英

在 React.js 中实现关注和取消关注按钮

[英]Implement follow and unfollow button in React.js

我正在尝试在我的应用中实现关注和取消关注按钮。

我一直试图在状态下更新它,但是当我单击“关注”按钮时,它会更改所有用户的按钮(不仅是单击的按钮)。

现在,如果用户已经在关注其他用户并在单击时使其工作,我对如何显示取消关注按钮感到有些困惑。

这是我的代码:

 class Followers extends React.Component { constructor(props) { super(props) this.state = { users: [], follower: [], following: [], button: "Follow" } } componentDidMount = () => { this.getUsers() } getUsers = () => { axios(`http://localhost:7001/api/users`) .then(response => { this.setState({ users: response.data}) console.log(response.data) }) .catch(error => { this.setState({ error: true }) }) } followUser = (e) => { e.preventDefault(); const userId = this.props.user[0].id const followedId = e.target.value axios.post(`http://localhost:7001/api/users/${userId}/follow/${followedId}`, { userId, followedId, createdAt: new Date().toISOString().slice(0, 10), updatedAt: new Date().toISOString().slice(0, 10) }) .then(response => { console.log(response.data) this.setState(state => ({ button: "Unfollow", loggedIn: !state.loggedIn })) }) .catch(error => { console.log(error) }) } unfollowUser = (e) => { e.preventDefault(); const userId = this.props.user[0].id const followedId = e.target.value axios.delete(`http://localhost:7001/api/users/${userId}/unfollow/${followedId}`) .then(response => { console.log(response) this.setState({ button: "Follow" }) }) .catch(error => { this.setState({ error: true }) }) } render() { const { users, button } = this.state const userId = this.props.user[0].id return ( <div> <h2>Users in Unax</h2> <ul> {users.map((user, index) => { if(user.id !== userId) { return ( <Card className="users" key= {index}> <CardBody> <CardTitle>{user.user_name}</CardTitle> <Button id="btn" value={user.id} onClick={this.followUser}>Follow</Button> <Button id="btn" value={user.id} onClick={this.unfollowUser}>Unfollow</Button> </CardBody> </Card> )} })} </ul> </div> ) } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我的最后一次尝试是添加两个按钮并设置条件,但是我想不出一种方法来比较关系是否已经存在,是否应该在后端完成?

看起来你所有的关注/取消关注按钮都链接到同一个状态,这意味着当它为真时它们都是真的,当它们为假时它们都是假的。

实现此目的的一种方法是在用户对象中有一个“跟随”属性。 然后,您可以根据该用户是否已被关注来更改按钮。

然后,您可以更新数据库和本地状态,以便为用户提供最灵敏的体验。

例如,您的用户对象可能类似于:

{id: 1, name: Bob, followed: false, image: ....}

这将使您了解按钮应该处于什么状态。

管理友谊数据库的深入描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM