反应本机redux reducer提供无限循环

时间:2020-11-01 11:13:38

标签: reactjs react-native redux expo reducers

我正在编写关于在状态Redux上的应用程序中为服务器+上的用户平衡添加点的功能,但是在状态Redux上,它会导致无限循环,并且我的应用程序崩溃IDK,原因是我的代码:

所以它的添加指向服务器,但是当我尝试更新时它会陷入无限循环 在应用程序中的工作方式:首先,我从asyncstorage获得ID,我从fetchUserData获取服务器中的积分,并在状态内进行处理,然后我想更新点oldPoints + 1

操作/用户:

export const fetchUserData = (id) => {
  return async (dispatch) => {
    try {
      //console.log(id);
      const response = await fetch(
        `xxx/users/${id}.json`,
        {
          method: "GET",
        }
      );
      if (!response.ok) {
        throw new Error("Something went wrong!");
      }
      const resData = await response.json();
      console.log("userName: " + resData.userName);
      console.log("Points: " + resData.points);
      const loadedUser = new User(id, resData.userName, resData.points);

      //console.log(resData);
      dispatch({
        type: SET_USER,
        user: loadedUser,
      });
    } catch (err) {
      throw err;
    }
  };
};
export const createUser = (userName, points) => {
  return async (dispatch) => {
    const response = await fetch(
      "xxx/users.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userName,
          points,
        }),
      }
    );
    if (!response.ok) {
      throw new Error("Something went wrong!");
    }
    const resData = await response.json();
    console.log(resData);
    AsyncStorage.setItem(
      "userData",
      JSON.stringify({
        id: resData.name,
        userName: userName,
        points: 0,
      })
    );
    dispatch({
      type: CREATE_USER,
      userData: {
        id: resData.name,
        userName,
        points,
      },
    });
  };
};
export const UpdateUser = (id, points) => {
  return async (dispatch) => {
    try {
      const response = await fetch(
        `xxx/users/${id}.json`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            points,
          }),
        }
      );
      if (!response.ok) {
        throw new Error("Something went wrong!");
      }
      dispatch({
        type: UPDATE_USER,
        userData: {
          points,
        },
      });
    } catch (err) {
      throw err;
    }
  };
};

减速机/用户:


import User from "../../models/User";
import { USERS, USER } from "../../data/data";
import {
  SET_USERS,
  CREATE_USER,
  UPDATE_USER,
  SET_USER,
} from "../actions/users";

const initialState = {
  users: USERS,
  user: USER,
};

const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_USERS:
      return {
        ...state,
        users: action.users,
      };
    case CREATE_USER:
      const newUser = new User(
        action.userData.id,
        action.userData.userName,
        action.userData.points
      );
      return {
        ...state,
        users: state.users.concat(newUser),
        user: newUser,
      };
    case UPDATE_USER:
      const newUser2 = state.user;
      newUser2.points = action.userData.points;
      return {
        user: newUser2,
      };
    case SET_USER:
      return {
        ...state,
        user: action.user,
      };
    default:
      return state;
  }
};

export default userReducer;

在APP中:


const MapScreen = (props) => {
  const [selectedLocation, setSelectedLocation] = useState();
  const [clicked, setClicked] = useState(false);
  const [map, setMap] = useState();
  const dispatch = useDispatch();
  const [UserId, setUserId] = useState();
  const UserPoints = useSelector((state) => state.users.user.points);

 useEffect(() => {
    const GetUserData = async () => {
      const userData = await AsyncStorage.getItem("userData");
      if (userData) {
        const res = JSON.parse(userData);
        //console.log("res.id: " + res.id);
        setUserId(res.id);
      }
    };
    GetUserData();
  }, [UserId]);

  const GoodAnswer = (distanceKm) => {
    console.log("userid: " + UserId);
    console.log("userPoints: " + UserPoints);

    if (UserId) dispatch(userActions.fetchUserData(UserId));
    if (UserId) {
      console.log("UPDATE!!!!");
      dispatch(userActions.UpdateUser(UserId, UserPoints + 1));
    }
    Alert.alert("You gave good answer!", "", [
      {
        text: "Okay",
        onPress: () => {
        },
      },
    ]);
  };

0 个答案:

没有答案