跨页面传递变量报错:ReferenceError: isLogged未定义
Hey there, let's fix that ReferenceError: isLogged is not defined issue you're hitting. The root problem is that you're trying to use isLogged in your render method, but you never properly declared it as part of your App component's state or instance properties. Right now, when you assign isLogged = RolesFunction() in componentDidMount, you're creating a global variable (which is bad practice anyway) and even worse, the render method runs before componentDidMount, so it won't see that value even if it was global.
Here's how to fix this properly:
Step 1: Initialize isLogged as component state
First, set up initial state in your App component so isLogged is accessible throughout the component:
export default class App extends Component { constructor(props) { super(props); // Initialize state with a default value this.state = { isLogged: false }; } componentDidMount(){ // Update state with the value from RolesFunction const loggedStatus = RolesFunction(); this.setState({ isLogged: loggedStatus }); }
Step 2: Access isLogged from state in render
Then, in your render method, pull isLogged from this.state instead of trying to use it as a standalone variable:
render() { const { isLogged } = this.state; // Destructure from state for cleaner code return ( <Router> <Scene key="homepage" component={Homepage} type="reset" leftTitle="Home" leftButtonTextStyle={{ color: "#ffffff" }} onLeft={() => Actions.authentication()} rightButtonTextStyle={{ color: "#ffffff" }} rightTitle={isLogged ? "Logout" : ""} // Simplified boolean condition onRight={isLogged ? () => App.logout() : () => {}} /> </Router> ) }
Step 3: Add safety checks to RolesFunction
Your RolesFunction has a hidden risk: if global.user or global.user.data is undefined (like if user data hasn't finished loading yet), it'll throw another error. Let's add guard clauses to prevent that:
export function RolesFunction(){ // Check if user data exists before accessing it if (!global.user?.data?.Roles) { return false; // Default to false if data isn't ready } const Roles = global.user.data.Roles; return Roles === "PLUS"; // Simplify the condition to a direct return }
Bonus: Handle async user data (if applicable)
If global.user.data loads asynchronously (e.g., from an API call), your RolesFunction might return false initially. You'll want to listen for when the user data updates and re-run RolesFunction to update the state. For example, if you're using a state management library or event emitter, subscribe to changes and call this.setState once the user data is fully loaded.
内容的提问来源于stack exchange,提问作者Jack23

