我有以下组件:
const ParentComponent: React.FC = () => {
const networkRef: any = useRef();
// Somewhere in the code, I call this
networkRef.current.filter(["id0, id1, id2"]);
return (
...
<VisNetwork
ref={networkRef}
/>
...
)
}
export default ParentComponent;
interface Props {
ref: any;
}
const VisNetwork: React.FC<Props> = forwardRef((props: Props, ref) => {
useImperativeHandle(ref, () => ({
filter(items: any) {
setFilterNodes(items);
nView.refresh();
}
}));
const [filterNodes, setFilterNodes] = useState<any[]>([]);
const filterNodesRef = useRef(filterNodes);
useEffect(() => {
filterNodesRef.current = filterNodes;
}, [filterNodes]);
...
// Some code to create the network (concentrate on the nodesView filter method)
const [nView, setNView] = useState<DataView>();
const nodesView = new DataView(nodes, {
filter: (n: any) => {
if (filterNodesRef.current.includes(n.id)) {
return true;
}
return false;
}
})
setNView(nodesView);
const network = new vis.Network(container, {nodes: nodesView, edges: edgesView}, options);
});
export default VisNetwork;
当我调用
network.current.filter([...])
,它将设置filterNodes
状态。此外,它应该设置 filterNodesRef
里面useEffect
.但是,
filterNodesRef.current
仍然是空数组。但是当我调用
network.current.filter([...])
第二次,只有 filterNodesRef.current
得到值和 DataView
能够过滤。为什么会这样?我以为
useRef.current
将始终包含最新值。
最佳答案
我终于通过调用 refresh()
解决了这个问题useEffect
中的方法而不是 filter()
方法:
useEffect(() => {
filterNodesRef.current = filterNodes;
nView.refresh();
}, [filterNodes]);
关于javascript - useRef 当前仅在第二次更新时获取其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62214408/