You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何通过AsyncStorage存储userId保持用户登录状态

Hey there! I see you're working on keeping a user logged in in your React Native app so you can call authenticated APIs after login. Let's walk through how to fix this step by step, since you mentioned you're new to React Native.

Step 1: Save Authentication Token After Login

When your login request succeeds, the API likely returns an authentication token (like a JWT) that you'll need to send with every subsequent authenticated API call. We'll store this token using AsyncStorage—React Native's built-in tool for persistent small-data storage.

Update your getAllDocuments method to save the token once login is successful:

getAllDocuments = async () => {
  try {
    const response = await fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: this.state.username,
        password: this.state.password,
      })
    });
    
    const responseDocs = await response.json();
    console.log("YOU HAVE SUCCESSFULLY LOGGED IN:", responseDocs);

    // Adjust this to match your API's actual token field (e.g., accessToken, jwt)
    if (responseDocs.token) {
      // Save token to persistent storage
      await AsyncStorage.setItem('authToken', responseDocs.token);
      // Update state to confirm user is signed in
      this.setState({ signedIn: true });
    }
  } catch (error) {
    console.error("Login failed:", error);
  }
};

Step 2: Check Login Status on App Start

Don’t call your login function directly in the constructor (async operations don’t work well there). Instead, check if a saved token exists when the component mounts—this lets users stay logged in even after closing and reopening the app.

Add these lifecycle methods:

componentDidMount() {
  this.checkAuthStatus();
}

checkAuthStatus = async () => {
  try {
    const token = await AsyncStorage.getItem('authToken');
    if (token) {
      // Token exists, mark user as signed in
      this.setState({ signedIn: true, checkedSignIn: true });
    } else {
      // No token, run the hardcoded login
      this.getAllDocuments();
      this.setState({ checkedSignIn: true });
    }
  } catch (error) {
    console.error("Failed to check auth status:", error);
    this.setState({ checkedSignIn: true });
  }
};

Step 3: Use the Token for Authenticated API Calls

When calling protected APIs, include the saved token in the request headers. Here’s an example:

fetchProtectedData = async () => {
  try {
    const token = await AsyncStorage.getItem('authToken');
    if (!token) {
      console.error("No auth token found—please login first");
      return;
    }

    const response = await fetch('https://example.dk/rest/YourProtectedEndpoint', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        // Send token in Authorization header (format depends on your API)
        'Authorization': `Bearer ${token}`
      }
    });

    const data = await response.json();
    console.log("Authenticated data:", data);
    // Update your state with the fetched data here
  } catch (error) {
    console.error("Failed to fetch protected data:", error);
  }
};

Step 4: Handle Logout (Optional)

If you want to let users log out, just remove the token from storage and reset the state:

logout = async () => {
  try {
    await AsyncStorage.removeItem('authToken');
    this.setState({ signedIn: false });
    console.log("User logged out successfully");
  } catch (error) {
    console.error("Logout failed:", error);
  }
};

Quick Notes for Your Code

  • I switched from .then() to async/await because it makes async code easier to read and debug—perfect if you’re new to React Native.
  • Double-check the token field name (like responseDocs.token) to match what your actual API returns. Some APIs use accessToken or jwtToken instead.
  • AsyncStorage is always asynchronous, so never try to access it without await or .then().

内容的提问来源于stack exchange,提问作者user8603159

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:57:57