【发布时间】:2021-02-24 05:36:45
【问题描述】:
大家好,我是反应 js 的新手,我有这段代码可以从列表中取消关注用户,代码正在运行,单击按钮时会关注所选用户,但问题是当我所有用户消失时单击取消关注按钮,我必须刷新页面才能看到列表中的其他用户。如何正确地做到这一点?我无法理解我在代码中做错了什么。
我希望它正常工作,因为当我们单击特定用户旁边的按钮时,只有该用户应该从列表中消失,而不是所有用户。
请看一下代码。
const [{user}, dispatch] = useStateValue();
const [followUsers, setfollowUsers] = useState([]);
function unfollowUser(otherUser, index) {
const updatedUsers = [...followUsers.results];
console.log([updatedUsers[index]]);
updatedUsers[index] = [updatedUsers[index]].filter(x => x.id !== user.id);
setfollowUsers(updatedUsers);
unfollowUserfunction("delete", otherUser);
}
async function unfollowUserfunction(method, otherUser) {
try {
await axiosInstance.request("/profile/" + otherUser.username + '/unfollow/', { method });
} catch (e) {
console.log(e);
}
}
{followUsers.results && followUsers.results.map((otherUser, index) => {
return (
<div className="searchRows" key={otherUser.id}>
<div className="searchRows__username">
<p>{otherUser.username}</p>
</div>
</div>
</div>
<div className="user__right">
<Tooltip title="unfollow">
<CheckIcon className="search__unfollow_icon"
onClick={() => {
unfollowUser(otherUser, index)
}}
/>
</Tooltip>
</div>
</div>
)
})
}
followUsers 来自控制台的响应。
{count: 2, next: null, previous: null, results: Array(2)}
count: 2
next: null
previous: null
results: Array(2)
0: {id: 3, username: "tester1", full_name: "Test1", profile_pic: "/media/pimage/default.png"}
1: {id: 4, username: "tester2", full_name: "Test2", profile_pic: "/media/pimage/default.png"}
length: 2
单击按钮时所有用户消失的原因是什么?帮助将不胜感激。谢谢
【问题讨论】:
-
[...followUsers.results] 也许应该 [...followUsers] ?你为什么在那里使用 .results ?
-
我在后端使用 django drf..所以如果我们提供分页,我们想要的确切数据将在结果对象中。
-
您在 console.log 中看到正确的值了吗?
-
是的。我可以看到正确的值。
-
我现在将使用从控制台获得的响应来更新问题。请务必看一下。
标签: javascript reactjs react-native jsx