有什么方法可以从React组件导出变量吗?

时间:2020-08-28 10:32:51

标签: javascript reactjs react-hooks

有没有办法从React组件导出变量以在我的自定义钩子中使用它?

代码如下:-

function App()
{
    const SignIn=()=>{
        //Some code here

        var userId = data.info.username;
        //Some code here
    }
    return(
        <div className='App'>
        ....
        </div>
    )
}

我需要在其他文件中使用userId。反正有做吗?

2 个答案:

答案 0 :(得分:0)

localStorage.setItem('userId',data.info.username);

并获取数据

const userId = localStorage.getItem("userId");

还了解有关redux和redux-persist
的信息 https://www.npmjs.com/package/redux

答案 1 :(得分:0)

您可以使用createcontext()-React.createContext()

userDetails.js
  
import React from "react";

const UserDetails = React.createContext({ user: null });

export default UserDetails ;

在App.js中

import UserDetails from "./userDetails"
function App()
{
    const SignIn=()=>{
        //Some code here

        var userId = data.info.username;
        //Some code here
    }
    return(
       <UserDetails.provider value={{user:userId}}>
        <div className='App'>
        ....
        </div>
        </UserDetails.provider>
    )
}

在孩子或需要的部分

import { useContext } from "react";
import UserDetails from "./userDetails"
  const userIdFetch = useContext(UserDetails);
  console.log(userIdFetch.user) //u will get user id