axios getitem('key')有时会传回null -在react应用程序中

8aqjt8rx  于 2022-11-23  发布在  iOS
关注(0)|答案(4)|浏览(131)

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

操作.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);
        });
}

我已经无计可施了!请帮帮我!

nhaq1z21

nhaq1z211#

这个localStorage.setItem()是一个异步任务,有时你运行let token = localStorage.getItem('idToken')刚好在setItem之后就会失败,所以你得到一个null,所以请把getItem的操作推迟一些,试一下,情况会有所不同:

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

x9ybnkn62#

将令牌逻辑(即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)...
vawmfj5a

vawmfj5a3#

在localstorage中设置一个键值,然后它在下一行立即返回null,这是不可能的。

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

仅当user.token值为空时才会发生这种情况。
这里的情况可能是你的thennable函数没有返回值给你的next函数,就像这样:

....
.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 }) =>  {
....
nhn9ugyo

nhn9ugyo4#

创建一个返回值或默认值的函数

const [hideTyC, setHideTyC] = useState(false);

  const loadTyCFlag = (): any => {
    if (
      localStorage.getItem("tyc") !== null ||
      localStorage.getItem("tyc") !== undefined
    ) {
      return localStorage.getItem("tyc") || false;
    }
  };

  useIonViewDidEnter(() => {
    hideTabBar();
    setHideTyC(loadTyCFlag());
  });

相关问题