React JS.页面上的所有用户对象都会消失,即使单击按钮时取消了单个用户的关注



大家好,我是react 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

当我点击按钮时,所有用户消失的原因是什么?非常感谢您的帮助。感谢

你的追随者是一个对象,你用数组设置它

function unfollowUser(otherUser, index) {
const updatedUsers = [...followUsers.results];
console.log([updatedUsers[index]]);
updatedUsers[index] = [updatedUsers[index]].filter(x => x.id !== user.id);
// an array is set to followers
setfollowUsers(updatedUsers);
unfollowUserfunction("delete", otherUser);
}

所以followers.result是未定义的,这就是你看到空屏幕的原因。

试试这个代码,这将替换results属性,这样UI将正确更新

function unfollowUser(otherUser, index) {
const updatedUsers = [...followUsers.results];
console.log([updatedUsers[index]]);
updatedUsers[index] = [updatedUsers[index]].filter(x => x.id !== user.id);
// an array is set to followers
setfollowUsers(Object.assign({},followUsers,{results:updatedUsers}));
unfollowUserfunction("delete", otherUser);
}

最新更新