我需要制作用户名片,点击关注按钮后,它会更改颜色和名称,并为关注添加 1。我从 API 收到这样的用户,12 个用户,我需要能够选择超过 1 个用户,我该怎么做,我想不通。 想试试 redux
但是我不明白如何在商店中标记录制按钮 那是我提出请求的代码。然后我把它记录在“用户”中,并通过地图,我渲染所有的卡片
export const UserList = () => {
const [users, setUsers] = useState([]);
const [userId, setUserId] = useState(null);
const [page, setPage] = useState(2);
const getUsersFromAPI = async () => {
const user = await fetchUsers();
setUsers(user);
};
const fetchNextPage = async () => {
setPage(prevPage => prevPage + 1);
const usersNext = await nextPageUsers(page, 3);
setUsers(prevUser => [...prevUser, ...usersNext]);
if (page === 4) {
setPage(1);
await nextPageUsers(page, 3);
return;
}
return usersNext;
};
useEffect(() => {
getUsersFromAPI();
}, []);
# const followind = (id, e) => {
#
# const userIdx = users.findIndex(user => user.id === id);
#
# if (userId === id) {
# setUserId(null);
# users[userIdx].followers--;
#
# return;
# }
#
# setUserId(id);
# users[userIdx].followers++;
# };
return (
<div>
{users && (
<ul className={css.list}>
{users.map(user => {
return (
<li key={user.id} className={css.containerItem}>
<div className={css.space}>
<button type="button" className={css.imageLogo}></button>
<div className={css.upperPart}></div>
<div className={css.middleLine}>
<img
className={css.userFoto}
src={user.avatar}
alt={user.name}
></img>
</div>
<div className={css.lowerPart}>
<p className={css.ps}> {user.tweets} Tweets</p>
<p className={css.ps}>
{' '}
{user.followers.toLocaleString('en-US')}
Followers
</p>
***<button
id={user.id}
className={
userId === user.id ? css.btnPress : css.btnFollow
}
type="button"
onClick={e => followind(user.id, e)}
>
{userId === user.id ? 'Following' : 'Follow'}
</button>***
</div>
</div>
</li>
);
})}
</ul>
)}
{page <= 4 && (
<button type="button" onClick={fetchNextPage}>
Next
</button>
)}
</div>
);
};```
如果我正确理解你的问题......
你需要一个“关注状态”的参数
为此,您需要将新参数添加到用户数组中的对象,例如,通过调用此参数“followingStatus”,并在点击时更改它的布尔值
您需要将新数组返回给您的 useState 钩子
const [users, setUsers] = useState([
{
id: 1,
followers: 0,
followingStatus: true,
},
{
id: 2,
followers: 56,
followingStatus: true,
},
{
id: 3,
followers: 1,
followingStatus: false,
},
{
id: 4,
followers: 4,
followingStatus: true,
},
{
id: 5,
followers: 9,
followingStatus: false,
},
]);
const followind = (id: number) => {
const newUsers = users.map((user) => {
if (user.id === id) {
return {
...user,
followers: user.followingStatus ? --user.followers : ++user.followers,
followingStatus: !user.followingStatus,
};
} else {
return user;
}
});
setUsers(newUsers);
};
<button
id={user.id}
className={user.followingStatus ? css.btnPress : css.btnFollow}
type="button"
onClick={e => followind(user.id, e)}
>
{user.followingStatus ? 'Following' : 'Follow'}
</button>