0

我有以下组件:

const ParentComponent: React.FC = () => {
    // Somewhere in the code, I set this to some value
    const [newType, setNewType] = useState<any>(undefined);

    // Somewhere in the code, I set this to true
    const [enableAddEdge, setEnableAddEdge] = useState(false);

    const addEdge = (data: any) => {
        console.log("newType", newType); // This is undefined
    }

    return (
    ...
        <VisNetwork 
            newType={newType}
            onAddEdge={addEdge}
            enableAddEdge={enableAddEdge}
        />
    ...
    )
}
export default ParentComponent;

interface Props {
    newType: any;
    onAddEdge: (data: any) => void;
    enableAddEdge: boolean;
}
const VisNetwork: React.FC<Props> = (props: Props) => {
    const options: any = {
        // Some vis-network specific option configuration
        manipulation: {
            addEdge: (data: any, callback: any) => props.onAddEdge(data);
        }
    }
    ...
    // Some code to create the network and pass in the options
    const network = new vis.Network(container, networkData, options);

    useEffect(() => {
        if (props.enableAddEdge) {
            // This confirms that indeed newType has value
            console.log("newType from addEdge", props.newType);

            // Call reference to network (I name it currentNetwork)
            // This will enable the adding of edge in the network.  
            // When the user is done adding the edge,
            // the `addEdge` method in the `options.manipulation` will be called.
            currentNetwork.addEdgeMode();
        }
    }, [props.enableAddEdge])

    useEffect(() => {
        if (props.newType) {
            // This is just to confirm that indeed I am setting the newType value
            console.log("newType from visNetwork", props.newType); // This has value
        }
    }, [props.newType]);
}
export default VisNetwork;

调用该addEdge方法时,newType状态变为未定义。我知道绑定,但我不知道是否可以使用它以及如何在功能组件中使用它。请告知如何获得newType价值。

另外,从VisNetwork,我想networkData从内部访问状态options.manipulation.addEdge。我知道这是不可能的,但有什么解决方法吗?此时我还需要访问networkData

4

1 回答 1

2

你需要useRef在这种情况下。它似乎const network = new vis.Network(container, networkData, options);只使用第一次渲染中的选项。或者类似的事情正在发生。

这可能与函数中存在闭包newType有关addEdge。所以它有陈旧的价值:https ://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function

为了解决这个问题,您需要useRef存储newType. 引用是可变的,因此它始终可以存储 newType 的当前值而无需重新渲染。

// Somewhere in the code, I set this to some value
const [newType, setNewType] = useState<any>(undefined);

const newTypeRef = useRef(newType);
useEffect(() => {
  // Ensure the ref is always at the latest value
  newTypeRef.current = newType;
}, [newType])

const addEdge = (data: any) => {
    console.log("newType", newTypeRef.current); // This is undefined
}
于 2020-05-22T23:32:38.797 回答