index.js
const [todo, setToDo] = useState([]);
useEffect(async() => {
socket.on("receive_message", (message) => {
let result = todos ? todos : [];
if (message.sendBy === 'user') {
let old_index;
if (result.length > 0) {
old_index = result.findIndex(item => item.id === message.senderId);
if (0 >= result.length) {
var k = 0 - result.length + 1;
while (k--) {
result.push(undefined);
}
}
result.splice(0, 0, result.splice(old_index, 1)[0]);
setTodos(result); // for testing
}]
}); }, [todos]);
const render =
todos &&
todos.map((item) => {
return (
<li
key={item.id}
className={activeId.id === item.id ? "person active-user" : "person"}
data-chat="person1"
onClick={(e) => historyAccess(item)}
>
<div className="user">
<img
src={item.profile_pic ? item.profile_pic : "avatars/12.png"}
alt="Profile Picture"
/>
</div>
<p className="name-time">
<span className="name">{item.name ? item.name : ""}</span>
{/* <span className="time">{}</span> */}
</p>
</li>
);
});
useEffect工作正常,settodos正在将其值更改为对象数组,但不会重新渲染。它工作得非常好,setTodos正在改变它的价值,并按预期工作,那么为什么会发生这种情况
问题
Array.prototype.splice在适当的位置对数组进行突变。将todos
状态的引用保存到局部变量result
,然后对其进行变异并将其保存回状态。数组引用永远不会更改。
此外,useEffect
钩子回调不能是async
。
解决方案
- 首先浅层复制数组,然后对其进行变异。这样React就可以协调状态实际上已经更新
- 由于您没有
await
任何内容,因此可以安全地删除async
声明
代码:
const [todos, setToDo] = useState([]); // <-- todos is already initially defined
useEffect(() => {
socket.on("receive_message", (message) => {
const result = [...todos]; // <-- shallow copy todos
if (message.sendBy === 'user') {
...
result.splice(0, 0, result.splice(old_index, 1)[0]); // <-- then mutate
setTodos(result);
}
});
}, [todos]);