useSelector不能及时加载状态

时间:2020-06-19 18:21:12

标签: reactjs redux react-redux

我正在使用ReactRedux进行我的项目。

我正在尝试使用token从商店的auth状态(包含我打算发送到服务器端的身份验证密钥)的useSelector状态中检索... const LikeButton = ({ postId }) => { const classes = useStyles(); const [isLiked, setIsLiked] = useState(false); const isMount = useIsMount(); const dispatch = useDispatch(); const { token } = useSelector((state) => state.auth); const { likedPostsIds } = useSelector((state) => state.likes); useEffect(() => { if (token) dispatch(fetchLikedPosts(token)); }, [token]); ... 字段但事实是,它没有及时加载。我该如何解决?

我将在我的代码中添加与此问题相关的以下部分:

LikeButton.js :(这是我尝试检索令牌的部分)

...

export const fetchLikedPosts = ({ token }) => (dispatch) => {
  fetch("http://localhost:8080/graphql", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: fetchLikedPostsQuery(),
  })
    .then((res) => res.json())

...

likeActions.js:

...

export const signIn = ({ password, email }) => (dispatch) => {
  dispatch({
    type: IS_AUTH_LOADING,
  });
  fetch("http://localhost:8080/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: signInQuery(password, email),
  })
    .then((res) => res.json())
    .then((resData) => {
      if (resData.errors) {
        dispatch(showNotification("User authentication has failed!", ERROR));
        dispatch({
          type: AUTH_ERROR,
        });
      } else {
        setLocalStorageAuth(resData.data.signIn.token, expiryDate);
        dispatch({
          type: SIGN_IN,
          payload: resData.data.signIn,
        });
      }
    })
    .catch((err) => {
      dispatch(
        showNotification(
          "User authentication has failed. Please try again later.",
          ERROR
        )
      );
      dispatch({
        type: AUTH_ERROR,
      });
      emptyLocalStorage();
    });
};
...

authActions.js

...

const initialState = {
  token: localStorage.getItem("token"),
  isAuth: localStorage.getItem("isAuth"),
  expiryDate: localStorage.getItem("expiryDate"),
  isLoading: false,
};

export default function authReducer(state = initialState, action) {
  switch (action.type) {
    case REGISTER_LOADING:
    case IS_AUTH_LOADING:
      return {
        ...state,
        isLoading: true,
      };
    case SIGN_IN:
      return {
        token: action.payload.token,
        isAuth: true,
        isLoading: false,
      };
    case AUTH_ERROR:
    case LOGIN_FAIL:
    case REGISTER_FAIL:
    case LOGOUT_SUCCESS:
      return {
        token: null,
        isAuth: false,
        isLoading: false,
      };
    case CREATE_USER:
      return {
        ...state,
        isLoading: false,
      };
    default:
      return state;
  }
}

...

auth.js:

pandas

1 个答案:

答案 0 :(得分:1)

fetchLikedPosts函数需要一个带有token键作为参数的对象。该效果当前仅通过token作为参数。试试

  useEffect(() => {
     // note the change from token to {token}
    if (token) dispatch(fetchLikedPosts({token}));
  }, [token]);