无法使用useState钩子访问prevState

时间:2020-11-06 22:18:12

标签: javascript reactjs next.js use-state

我有一个组件试图捕获某事物的previousState,但是无论它不断返回初始值是什么。这使我相信正在发生重新渲染,因此它始终默认为初始状态。

import React, { useState } from "react";

import { InfoWindow } from "../info-window/info-window";
import { LocationProps } from "../../../interfaces/location-inteface";

export interface Props {
    lat: number;
    lng: number;
    location: LocationProps;
}

type PreviousLocation = {
    isActive: boolean;
    location: Props["location"];
};

export const InStoreMarker: React.FC<Props> = (props: Props) => {
    const { location } = props;
    const [isActive, setIsActive] = useState(false);
    const [infoWindowVisible, setActiveInfoWindowVisible] = useState(false);
    const [activeLocation, setActiveLocation] = useState({
        isActive: false,
        location: null
    });
    const [previousLocation, setPreviousLocation] = useState(null);


    const onClick = (location: LocationProps, prevLocation: PreviousLocation) => {
        setIsActive(true);
        setActiveInfoWindowVisible(true);
        setPreviousLocation(prevLocation);
        setActiveLocation({
            isActive: true,
            location: location,
        });
        console.log("Click previousLocation", previousLocation);
        console.log("Click location", location);
    };

    const onClose = (value: boolean) => {
        setIsActive(value);
        setActiveInfoWindowVisible(value);
    };

    useEffect(() => {
        console.log("activeLocation", activeLocation);
        console.log("previousLocation", previousLocation);
    }, [previousLocation, activeLocation]);

    return (
        <div className={styles.inStoreMarkerContainer}>
            {isActive && infoWindowVisible && (
                <InfoWindow
                    location={location}
                    onClose={onClose}
                />
            )}
            <div
                className={styles.inStoreMarker}
                onClick={() => onClick(location, activeLocation)}
            />
        </div>
    );
}

setActiveLocation回调内部的控制台日志不断返回

{
    id: null,
    isActive: false,
    location: null
}

我尝试创建一个usePrevious函数,如https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state所示,但这总是返回undefined,所以我现在有点卡住了。

2 个答案:

答案 0 :(得分:0)

也许自定义钩子可以帮助您?

也许 usePrevious可以解决此问题而无需在实际组件中添加样板

答案 1 :(得分:-1)

也许会有所帮助。

const onClick = useCallback(({ location: { id, isActive, location } }) => {
  setActiveLocation((prevState: PreviousLocation) => {
    console.log("previousState", prevState);
    return new Map(prevState).set(id, isActive, location);
  });
}, []);