简体   繁体   English

React Js - 使用外部变量达到内部函数

[英]React Js - reaching inner functions with outer variables

I got a quick question.我有一个快速的问题。 Is there anyway to have a global variable that reaches the inne functions in this code.无论如何,是否有一个全局变量可以到达此代码中的内部函数。 I other words i don't want to have to repeat the line "const user = JSON.parse(localStorage.getItem("user"));"换句话说,我不想重复这行“const user = JSON.parse(localStorage.getItem("user"));”

but rather have a global variable for the user.accessToken而是为 user.accessToken 提供一个全局变量

import axios from "axios";
const API_URL = "http://localhost:8081/api/files/";

const upload = (file, onUploadProgress) => {
  const user = JSON.parse(localStorage.getItem("user"));
  let formData = new FormData();
  formData.append("file", file);

  return axios.post(API_URL + "upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: "Bearer " + user.accessToken,
    },
    onUploadProgress,
  });
};

const getFiles = () => {
  const user = JSON.parse(localStorage.getItem("user"));
  return axios.get(API_URL + "getall", {
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + user.accessToken,
    },
  });
};

const FileUploadService = {
  upload,
  getFiles,
};

export default FileUploadService;

I'd suggest using React Context https://reactjs.org/docs/context.html我建议使用 React Context https://reactjs.org/docs/context.html

Firstly, create a new context named userContext, or something fancy首先,创建一个名为 userContext 的新上下文,或者一些花哨的东西

const UserContext = React.createContext();

Then create a provider for this context然后为这个上下文创建一个提供者

function UserContextProvider() {
    const user = JSON.parse(localStorage.getItem("user"));
    return <UserContext.Provider value={user} />

}
// and then the hook for accessing the context
function useUserContext() {
   const context = React.useContext(UserContext);
   if (!context) {
      throw new Error("useUserContext: must be used within a UserContextProvider");
   }
   return context;

}

Then you wrap all of your components that should have access to the context.然后包装所有应该可以访问上下文的组件。

<UserContextProvider>
... all other components
</UserContextProvider>

And to access the user data in your component use并访问组件中的用户数据,请使用

function SomeComponent(){
   const user = useUserContext();
   return ....
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM