gpt4 book ai didi

javascript - React Hooks setState 函数未设置状态

转载 作者:行者123 更新时间:2023-11-28 03:33:39 25 4
gpt4 key购买 nike

我正在尝试构建一个聊天应用程序,并且我有一个用于选择要添加到聊天中的用户的功能。它位于以下组件中(为了简洁起见,我省略了导入语句和其中一个函数):

const AddUserBox = (props) => {

// context:
const { friends, getFriends, user, whoToMsg } = useContext(AppContext);

// state:
const [friendsDisplay, setFriendsDisplay] = useState();
const [selected, setSelected] = useState();

const getFriendsDisplay = async function() {
if (!friends) await getFriends(user.username);

if (friends) {
let currentFriend;
let result;
let friendsInfo = [];

friends.sort();

for (let i = 0; i < friends.length; i++) {

if (friends[i].user_1 === user.username) {
currentFriend = friends[i].user_2;
} else {
currentFriend = friends[i].user_1;
}

if (currentFriend === whoToMsg) {
return;
} else if (typeof whoToMsg === Array) {
if (whoToMsg.includes(currentFriend)) return;
}

await fetch('/proxy/get-user-update', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type':'application/json'
},
body: JSON.stringify({username: currentFriend})
})
.then(results => results.json())
.then(data => result = data)
.catch(err => console.error(err));

friendsInfo.push(result);
}

setFriendsDisplay(friends.map((friend, i) => {
return <div
className="add-user-friends-button"
key={i}
i={i}
onClick={(e) => {selectUser(e, friend)}}
>
{friendsInfo[i].name}
</div>
}));
}
}

const selectUser = function(e, friend) {
let newArr = [];
let currentFriend;

if (friend.user_1 === user.username) {
currentFriend = friend.user_2;
} else {
currentFriend = friend.user_1;
}

if (selected) {
newArr = [...selected];
if (selected.includes(currentFriend)) {
e.target.style.backgroundColor = "";
newArr.splice(newArr.indexOf(currentFriend), 1);
setSelected(newArr);
return;
}
}

newArr.push(currentFriend);
newArr.sort();

e.target.style.backgroundColor = "#E6FCFF";
setSelected(newArr);
console.log(selected);
}

return (
<div className="add-user">
<span>Add users to chat:</span>
<div className="add-user-friends">
{friendsDisplay}
</div>
<button onClick={() => props.close()}>Close</button>
<button onClick={() => addUsers()}>Add users</button>
</div>
);
}

这个想法是,您从列表中选择一个用户,并将其添加到选定用户的数组中,这样当他们单击“添加用户”按钮时,用户就会添加到聊天中。出于某种原因setSelected(newArr ) 不会将状态设置为新数组。谁能帮助我理解/解决这个问题?

最佳答案

由于 setState 是一个异步方法,因此当您立即调用它时,并不总是能获得预期的值。您可以将回调方法传递给 setState。如果将 console.log 语句移至此处,您应该会看到预期的结果。

这里有一些信息: https://dev.to/dance2die/accessing-react-state-right-after-setting-it-2kc8

关于javascript - React Hooks setState 函数未设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com