useRef 当前仅在第二次更新时获取其值

iPh*_*Dev 5 javascript typescript reactjs visnetwork

我有以下组件:

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;
Run Code Online (Sandbox Code Playgroud)

当我调用时network.current.filter([...]),它会设置filterNodes状态。此外,它应该filterNodesRefuseEffect.

但是,filterNodesRef.current仍然是空数组。

但是当我network.current.filter([...])第二次打电话时,只有这样才能filterNodesRef.current得到值并且DataView能够过滤。

为什么会这样?我认为useRef.current将始终包含最新值。

iPh*_*Dev 4

我最终通过调用refresh()方法内部的方法useEffect而不是filter()方法解决了这个问题:

useEffect(() => {
    filterNodesRef.current = filterNodes;
    nView.refresh();
}, [filterNodes]);
Run Code Online (Sandbox Code Playgroud)