将位于另一个文件中的状态设置为位于 App.js 中的状态

huangapple go评论72阅读模式
英文:

setState to a state located in App.js from another file

问题

我有一个名为api.js的文件,其中存储了我的axios配置。我目前正在使用axios,并且希望在任何axios请求接收到带有401状态码的响应时注销用户。现在我的问题是如何从api.js文件中清除App.js中的状态?

/* api.js */
import axios from "axios";

const api = axios.create();

api.interceptors.request.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      /* 清除App.js中的所有状态 */
      console.log("未经授权");
    }
    return Promise.reject(error);
  }
);

/* App.js中的状态 */
const [user, setUser] = useState(null);
const [shifts, setShifts] = useState([]);
const [jobs, setJobs] = useState([]);
英文:

I have a file called api.js where I have my axios configs stored. I'm currently using axios and I want to log the user out if any axios request receives a response with a 401 status code. Now my problem is that how can I clear the states in App.js from the api.js file?

/* api.js */
import axios from "axios";

const api = axios.create();

api.interceptors.request.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      /* clear all states in App.js */
      console.log("unauthenticated");
    }
    return Promise.reject(error);
  }
);

  /* states in App.js */
  const [user, setUser] = useState(null);
  const [shifts, setShifts] = useState([]);
  const [jobs, setJobs] = useState([]);

答案1

得分: 1

我假设你正在使用 useState 钩子来管理 App 组件中的状态。这实际上并不是直接在组件之外操作 React 组件状态的方式。

要解决这个问题,我建议也许可以使用 Context API。这样你就可以在需要的地方使用它,比如在你的 api.js 文件中。

下面是一个代码示例用法:AuthContext.js

import React, { useState, createContext } from 'react';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [shifts, setShifts] = useState([]);
  const [jobs, setJobs] = useState([]);

  const logout = () => {
    setUser(null);
    setShifts([]);
    setJobs([]);
  };

  return (
    <AuthContext.Provider value={{ user, shifts, jobs, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

在 App 级别 - 添加上下文

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { AuthProvider } from './AuthContext';

ReactDOM.render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

最后在你的 api.js 文件中进行相应的更改

import axios from 'axios';
import { useContext } from 'react';
import { AuthContext } from './AuthContext';

const api = axios.create();

api.interceptors.request.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response.status === 401) {
      const { logout } = useContext(AuthContext);
      logout();
      console.log("未经授权");
    }
    return Promise.reject(error);
  }
);
英文:

I am assuming you are using useState hook manage states in the App component. Its not really the way for you to directly manipulate the state of the react component outside of that component.

To fix it, i would suggest maybe using Context API. This way you can consume it where its needed - in your case the api.js file.

Here is an code example usage: AuthContext.js

import React, { useState, createContext } from &#39;react&#39;;

export const AuthContext = createContext();

export const AuthProvider = ({ children }) =&gt; {
  const [user, setUser] = useState(null);
  const [shifts, setShifts] = useState([]);
  const [jobs, setJobs] = useState([]);

  const logout = () =&gt; {
    setUser(null);
    setShifts([]);
    setJobs([]);
  };

  return (
    &lt;AuthContext.Provider value={{ user, shifts, jobs, logout }}&gt;
      {children}
    &lt;/AuthContext.Provider&gt;
  );
};

At the App level - add the context:

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import App from &#39;./App&#39;;
import { AuthProvider } from &#39;./AuthContext&#39;;

    ReactDOM.render(
      &lt;React.StrictMode&gt;
        &lt;AuthProvider&gt;
          &lt;App /&gt;
        &lt;/AuthProvider&gt;
      &lt;/React.StrictMode&gt;,
      document.getElementById(&#39;root&#39;)
    );

and finally edit your api.js file with changes as such:

import axios from &#39;axios&#39;;
import { useContext } from &#39;react&#39;;
import { AuthContext } from &#39;./AuthContext&#39;;

const api = axios.create();

api.interceptors.request.use(
  (response) =&gt; {
    return response;
  },
  async (error) =&gt; {
    if (error.response.status === 401) {
      const { logout } = useContext(AuthContext);
      logout();
      console.log(&quot;unauthenticated&quot;);
    }
    return Promise.reject(error);
  }
);

huangapple
  • 本文由 发表于 2023年7月14日 00:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定