【问题标题】:localstorage.getitem('key') sometimes returns null - in a react applocalstorage.getitem('key') 有时返回 null - 在反应应用程序中
【发布时间】:2018-03-08 19:24:04
【问题描述】:

这是一个非常奇怪的问题!我正在尝试构建一个在localstorage 中设置JWT 令牌的登录表单。然后其他表单使用该令牌发布请求。我可以在我的console.log 中看到令牌,但有时(比如 5 次中有 3 次),当我设置 localstorage.getitem('idToken') 时,它显示为 null。当我从我的 loginUser() 函数中删除 console.log(idToken) 时,这种行为最为明显(actions.js 文件中的代码 - 如下所示)。我究竟做错了什么?我的应用是使用 React/Redux 构建的。

action.js

export function loginUser(creds) {

const data = querystring.stringify({_username: creds.username, _password: creds.password});

let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: data
};

return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds));

    return fetch(BASE_URL+'login_check', config)
        .then(response =>
            response.json().then(user => ({ user, response }))
        ).then(({ user, response }) =>  {
            if (!response.ok) {
                // If there was a problem, we want to
                // dispatch the error condition
                dispatch(loginError(user.message));
                return Promise.reject(user)
            } else {

                localStorage.setItem('idToken', user.token);
                let token = localStorage.getItem('idToken')
                console.log(token);
                // if I remove this log, my token is returned as null during post. 
                dispatch(receiveLogin(user));
            }
        }).catch(err => console.log("Error: ", err))
}
}

这是我的 POST 请求:

import axios  from 'axios';
import {BASE_URL} from './middleware/api';
import {reset} from 'redux-form';

 let token = localStorage.getItem('idToken');
 const AuthStr = 'Bearer '.concat(token);

let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};

export default (async function showResults(values, dispatch) {
console.log(AuthStr);
axios.post(BASE_URL + 'human/new', values, headers)
    .then(function (response) {
        console.log(response);          
        alert("Your submit was successful");
        //dispatch(reset('wizard'));
    }).catch(function (error) {
        console.log(error.response);
        alert(error.response.statusText);
    });
 });

这个GET 请求每次都有效,顺便说一句:

getHouses = (e) =>  {
    let token = localStorage.getItem('idToken') || null;
    const AuthStr = 'Bearer '.concat(token);
    axios.get(BASE_URL + 'household/list', { headers: { Authorization: AuthStr } }).then((response) =>
        {
            let myData = response.data;

            let list = [];
            let key =[];
            for (let i = 0; i < myData._embedded.length; i++) {
                let embedded = myData._embedded[i];
                list.push(embedded.friendlyName);
                key.push(embedded.id);
            }

            this.setState({data: list, key: key});

        })
        .catch((error) => {
            console.log('error' + error);
        });
}

我无计可施!请帮忙!

【问题讨论】:

    标签: javascript reactjs redux jwt axios


    【解决方案1】:

    将您的令牌逻辑(即localStorage.getItem('idToken');)移动到导出的函数中,它应该可以工作

    export default (async function showResults(values, dispatch) {
      let token = localStorage.getItem('idToken');
      const AuthStr = 'Bearer '.concat(token);
    
      let headers ={
       headers: { 'Content-Type':'application/json','Authorization' : AuthStr 
      }
     };
     axios.post(BASE_URL + 'human/new', values, headers)...
    

    【讨论】:

    • 如果我在函数之外设置它为什么不起作用?是因为async吗?
    • @SamiaRuponti 这个解决方案对你有用吗?我会解释原因。
    【解决方案2】:

    localStorage.setItem()是一个异步任务,有时你在setItem之后运行let token = localStorage.getItem('idToken')会失败,所以你得到一个null,所以请把getItem操作放在后面,试一试,它会不同:

    setTimeout(function() {
        let token = localStorage.getItem('idToken');
        dispatch(receiveLogin(user));
    }, 50);
    

    【讨论】:

      【解决方案3】:

      不会出现这样的情况:您在 localstorage 中设置了一个键值,然后它立即在下一行返回 null。

      localStorage.setItem('idToken', user.token);
      let token = localStorage.getItem('idToken');
      

      仅当您的 user.token 值为 null 时才会发生这种情况。

      也许这里的情况是你的 thennable 函数没有像这样将值返回给你的下一个 then:

      ....
      .then(response =>
           // return response to your next then function
           // this will be passed to next then function as params
           return response.json();
      ).then(({ user, response }) =>  {
      ....
      

      【讨论】:

        猜你喜欢
        • 2020-11-10
        • 2018-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-16
        • 1970-01-01
        • 2015-06-03
        • 1970-01-01
        相关资源
        最近更新 更多