代码之家  ›  专栏  ›  技术社区  ›  soalrib

使用ReactJS从API刷新令牌

  •  0
  • soalrib  · 技术社区  · 8 年前

    早上好,我有一个REST API,它需要一个令牌来访问它我已经设法用Reactjs生成了令牌,但是现在我需要它不时地刷新为此,我需要以某种方式存储令牌,以便再次获取API我在尝试本地存储,但没有成功有什么帮助吗?

    constructor(props) {
            super(props);
            this.state = {
                models: [],
                isLoaded: false
            };
        }
    
    componentDidMount() {
        const email = myEmail;
        const pass = myPass;
        const url = url;
    
        fetch(url + '/api-token-auth/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }, body: JSON.stringify({
                email: email,
                password: pass,
            })
        })/*, fetch(url + "/api-token-refresh/", {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }, body: JSON.stringify({
                token: token
            })
        })*/
        // <-- code for refreshing token, working on it
    
            .then(res => {
                if (res.ok) {
                    return res.json();
                } else {
                    throw Error(res.statusText);
                }
            })
            .then(json => {
                this.setState({
                    isLoaded: true,
                    token: json
                });
    
                let token = this.state.token;
                console.log('var token: ', token);
    
                localStorage.setItem('token', token);
            })
            .catch(error => console.error(error));
    
            const token = localStorage.getItem('token');
            console.log('localStorage w token: ', token);
    }`
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Lovegood    8 年前

    据我所知,错误在第二个承诺处理程序中。 setState({})是一个异步函数 这意味着状态是在.then函数中的其他指令之后设置的。

    .then(json => {
            this.setState({
                isLoaded: true,
                token: json
            });
    
            /*the above function is executed after below statements are executed beecause the nature of this.setState is asynchronous*/
            /*and that is why you must be getting an old or garbage value from this.state.token then in localStorage */
    
            let token = this.state.token;
            console.log('var token: ', token);
    
            localStorage.setItem('token', token);
        })
    

    要解决这个问题: 您可以在此.setState中提供回调函数 只有在设置了状态之后才执行 ! 万岁这样地:

    .then(json => {
            this.setState({ isLoaded: true, token: json }, () => {
              //this is the callback function
              //you should do tasks which depend on new state here
              let token = this.state.token;
              console.log('var token: ', token);
              localStorage.setItem('token', token);
            });
     })
    

    dbvt10 在上面的评论中也指出了同样的问题。

    您可以在上阅读有关setState回调函数的更多信息 this awesome article 由Medium.com提供。 ^_^

        2
  •  0
  •   soalrib    8 年前

    这是我的解决方案,我需要将令牌存储为字符串 JSON.stringify 然后,当我需要再次使用它时,使用 JSON.parse .

    componentDidMount() {
        const email = myEmail;
        const pass = myPass;
        const url = url;
    
            fetch(url + '/api-token-auth/', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                }, body: JSON.stringify({
                    email: email,
                    password: pass,
                })
            }).then(res => {
                if (res.ok) {
                    return res.json();
                } else {
                    throw Error(res.statusText);
                }
            }).then(json => {
                this.setState({
                    isLoaded: true,
                    token: json
                }, () => {
                    let tokenJson = JSON.stringify(json);
                    localStorage.setItem('token', tokenJson);
                });
            }).catch(error => console.error('erro:' + error));
    
    
            fetch(url + '/api-token-refresh/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }, body: (localStorage.getItem('token'))
            }).then(res => {
                if (res.ok) {
                    return res.json();
                } else {
                    throw Error(res.statusText);
                }
            }).then(json => {
                this.setState({
                    isLoaded: true,
                    token: json
                }, () => {
                    let tokenJson = JSON.stringify(json);
                    localStorage.setItem('token', tokenJson);
                });
            })
    
        }