gpt4 book ai didi

reactjs - react 钩子(Hook) - 调度操作后未调用useEffect

转载 作者:行者123 更新时间:2023-12-04 09:45:08 33 4
gpt4 key购买 nike

我有一个可以喜欢/不喜欢汽车的按钮。

国家存储usersLikedCars这是一个数组。

当用户点击like/dislike按钮(同一个按钮),API 调用要么是 POST 要么是 DELETE,它更新 db 并返回 1 多或 1 行 usersLikedCars .

此操作完成后,我想:

  • 循环浏览更新的 usersLikedCars数组
  • 检查汽车是否被喜欢/不喜欢
  • 将按钮颜色更新为 red=liked, blue=notLiked

  • 当前行为
  • 按钮颜色仅在我离开当前页面并返回时才会更新
  • 在操作中,我可以记录返回的 API 数据,并且它会正确更新

  • 预期行为
  • 我期待 usersLikedCars在组件中更新(它是计数)并通过检查新添加的汽车是否是更新数组的一部分来调用基本上更新按钮颜色的函数。

  • 查看 this 中的答案链接,我添加了 useEffect我在其中调度获取更新的 usersLikedCars 的操作——至少我是这么认为的。它仅在页面首次呈现时调用。

    另外, useEffect强制我包装 isCarLikedsetLikeButtonColoruseCallback我不是 100% 肯定是正确的..

    有人可以指出我正确的方向吗?
    const CarScreen = ({ route }) => {
    // props
    const { params } = route;
    const { car } = params;
    // member variables
    const carTitle = `#${car.title}`;
    const carLikeCount = car.hit_count ? car.hit_count : 0;
    const carBirthday = moment(car.created_at).format('MMMM Do YYYY');
    const carLikeButtonColor = useRef('');
    // redux
    const dispatch = useDispatch();
    const user = useSelector((state) => state.user.user);
    const usersLikedCars = useSelector(
    (state) => state.usersLikedCars.items,
    );

    /**
    * Call this function when car is liked/unliked
    * and when like button color needs to be updated
    */
    useEffect(() => {
    dispatch(fetchUsersLikedCars());

    // set the like button's color: red - LIKED, blue - NOT LIKED
    setLikeButtonColor();
    }, [dispatch, setLikeButtonColor]);

    /**
    * Method for liking a car
    */
    const handleLikeOrUnlikeCar = async () => {
    // check if user already liked this car
    const carAlreadyLikedByUser = isCarLiked();

    if (carAlreadyLikedByUser) {
    // find the car in user's liked car state array to "unlike"
    const carToDelete = usersLikedCars.find(
    (usersLikedCar) => usersLikedCar.title === car.title,
    );
    // unlike it
    try {
    await console.log(
    'BEFORE remove usersLikedCars',
    usersLikedCars,
    );

    await remove({
    uid: carToDelete.uid,
    });
    await dispatch(fetchUsersLikedCars());
    await console.log(
    'AFTER remove usersLikedCars',
    usersLikedCars,
    );
    } catch (error) {
    console.error(error);
    }
    } else {
    // like it

    try {
    await console.log('BEFORE add usersLikedCars', usersLikedCars);
    await add({
    title: car.title,
    user_uid: user.uid,
    car_uid: car.uid,
    });
    await dispatch(fetchUsersLikedCars());
    await console.log('AFTER add usersLikedCars', usersLikedCars);
    } catch (error) {
    console.error(error);
    }
    }
    };

    const isCarLiked = useCallback(
    () =>
    usersLikedCars.some(
    (usersLikedCar) => usersLikedCar.title === car.title,
    ),
    [usersLikedCars, car.title],
    );

    /**
    * Set color of car like button
    */
    const setLikeButtonColor = useCallback(() => {
    // look through user's liked cars and see if the current one is in there already
    const carAlreadyLikedByUser = isCarLiked();

    // if user liked this car already, color = RED else BLUE
    carLikeButtonColor.current = carAlreadyLikedByUser
    ? Colors.loveRed
    : Colors.defaultColor;
    }, [isCarLiked]);

    ....
    }

    行动
    export const fetchUsersLikedCars = () => async (dispatch) => {
    const usersLikedCars = await find();

    console.log('ACTION usersLikedCars', usersLikedCars); // value is correctly updated here
    return dispatch({
    type: FETCH_USERS_LIKED_CARS,
    payload: usersLikedCars,
    });
    };

    最佳答案

    你需要把 usersLikedCarsuseEffect 的依赖项中这样每当它改变时,useEffect被触发。

    要做到这一点,您可以拥有另一个 useEffect除了你已经拥有的(拥有多个 useEffects 是非常正常和合法的),它不会触发 dispatch再次,所以它不会进入无限状态

     useEffect(() => {
    setLikeButtonColor();
    }, [usersLikedCars]);

    关于reactjs - react 钩子(Hook) - 调度操作后未调用useEffect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62164670/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com