亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 ReactJS + Redux 中同時從 LocalStorage 寫入然后讀取

在 ReactJS + Redux 中同時從 LocalStorage 寫入然后讀取

慕娘9325324 2022-12-08 15:32:35
我正在嘗試寫入 localStorage,然后從 localStorage 身份驗證令牌中讀取以訪問 API。export const authLogin = (username, password) => {  return (dispatch) => {    dispatch(authStart());    axios      .post(" http://localhost:8000/rest-auth/login/", {        username: username,        password: password,      })      .then((res) => {        const token = res.data.key;        const expirationDate = new Date(new Date().getTime() + 3600 * 1000);        try {          localStorage.setItem("token", token);          localStorage.setItem("expirationDate", expirationDate);          dispatch(authSuccess(token));          dispatch(checkAuthTimeout(3600));        } catch (error) {          console.log("error storing data");        }      })      .catch((err) => {        dispatch(authFail(err));      });  };};然后從我想從 localStorage 中讀取的 ReactJS 方法:import axios from "axios";import { endpoint } from "./constants";var token = localStorage.getItem("token");export const authAxios = axios.create({  baseURL: endpoint,  headers: {    Authorization: `Token ${token ? localStorage.getItem("token") : null}`,  },});class OrderSummary extends React.Component {  _isMounted = false;  state = {    data: null,    error: null,    loading: false,  };  componentDidMount() {    this._isMounted = true;    this.handelFetchOrder();  }  componentWillUnmount() {    this._isMounted = false;  }  handelFetchOrder = () => {    this.setState({ loading: true });    authAxios      .get(orderSummaryURL)      .then((res) => {        this.setState({ data: res.data, loading: false });        console.log(res.data);      })      .catch((err) => {        if (err.response.status === 404) {          this.setState({            error: "You currently do not have any order",            loading: false,          });        } else {          this.setState({ error: err, loading: false });        }      });  };我的問題是當我從 localStorage讀取時。如果令牌變為空。這會導致 401 api 代碼,因為我們無法讀取令牌以將其傳遞給 api 以獲取結果。但是,如果我刷新網絡瀏覽器 (F5),則一切正常。
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

在您的示例中,您在加載文件時為 axios 設置令牌。這意味著只有在應用程序加載時,而不是在您登錄后。所以那個localStorage時候那個項目是空的。


所以解決方案是為 axios 設置攔截器而不是你的實例authAxios:


const App = (props) => {


  // This will trigger when only once when page refreshes

  useEffect(() => {

    axios.interceptors.request.use(

      (config) => {

        config.headers = {

          ...config.headers,

          Authorization: `Token ${token ? localStorage.getItem("token") : null}`

        };


        return config;

      },

      (error) => {

        props.dispatchRedirectToLoginPage()

        return Promise.reject(error);

      }

    );

  }, [])


  return <div>Your app</div>

}

這樣每個請求都會執行這個函數,它會從 localStorage 中獲取令牌。


您進行的每個 api 調用都可以使用axios.get(...)或使用您需要的任何方法。


查看完整回答
反對 回復 2022-12-08
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號