【发布时间】:2020-10-20 20:15:56
【问题描述】:
我正在开发一个基于对象键管理字符串数组的函数。假设它看起来像这样:
import React, { useState, useEffect } from "react";
import FieldContext from "../contexts/FieldContext";
import io from "socket.io-client";
const [socket, setSocket] = useState(null);
// the `data` array gets changed every second due to a WebSocket, in case that's important
const [data, setData] = useState({ foo: [], bar: [] });
const [connections, setConnections] = useState(["conn1", "conn2"]);
const { checkedFields } = useContext(FieldContext); // ["foo", "moo"];
useEffect(() => {
setConnections(prevConnections => {
// The code below does the following:
// Loop through the temporary connections (which is a copy of checkedFields)
// A. if `tempConn` is a key in the `data` object, push the name with `update_` prefix to the `_conns` array
// B. If not, just push it without a prefix to the `_conns` array
// Since the `checkedFields` array is ["foo", "moo"], the first element will get the prefix,
// the other won't and will just get pushed.
let _tempConns = [...checkedFields];
let _conns = [];
_tempConns.forEach(tempConn => {
if (data[tempConn] !== undefined) _conns.push(`update_${tempConn}`);
else _conns.push(tempConn);
});
return _conns;
});
}, [checkedFields]);
// the websocket hook
useEffect(() => {
const _socket = io(WS_URI);
_socket.on("info", data => {
// some magic happens here to add to the `data` object which is not important for this question
});
setSocket(_socket);
}, [])
我在使用这个钩子时收到以下警告:React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array。我明白,但如果我在依赖数组中包含data,我会得到大量不必要的更新。我该如何防止这种情况发生? (请不要使用// eslint-disable-next-line)
【问题讨论】:
-
当
data发生变化时,您还有其他需要运行的效果吗? -
是的,我有一个,这只是演示代码
-
你好。通过您的更新(websocket),我发现了一个类似的示例。它正在使用 Reducer ^^: adamrackis.dev/state-and-use-reducer 。希望对你有用
-
我打算建议
const data = useRef({foo: [], bar: [] })使用套接字直接更新data.current属性值...但是如果您希望在data的引用更改时运行其他效果,那么它不是可行且行不通...
标签: reactjs react-hooks use-effect use-state