简体   繁体   English

React-native无法找到简单的js学习变量

[英]React-native Can't find variable simple js learning

After setup a simple token login based in a tutorial and the react docs the react-native shows Can't find variable: isLogged i've tried to pass the getToken to isLogged var but show this Can't find variable error. 在基于教程和react docs的基础上设置了简单的令牌登录后,react-native会显示Ca n't find variable:isLogged我试图将getToken传递给isLogged var,但显示此Cannot find variable错误。

sorry, as i'm trying to learn js and the react in general terms. 抱歉,我正在尝试学习js和一般的反应。

in this case if the token exists redirect the user to home otherwise redirect to login. 在这种情况下,如果令牌存在,则将用户重定向到首页,否则将重定向到登录名。 so, can anyone please spare a hint about how to pass a variable as a function in this scenario? 因此,在这种情况下,任何人都可以保留关于如何将变量作为函数传递的提示吗?

here is the code: 这是代码:

import React, { Component } from 'react';

import { AsyncStorage } from 'react-native';

import { NativeRouter, Route, Link, Redirect, withRouter } from 'react-router-native'

import Login from './pages/Login';
const AUTH_TOKEN = 'auth_token';
const isLogged = getToken();

class App extends Component {

    componentWillMount() {
        this.getToken();

    }

    async getToken() {
        try {
            let authToken = await AsyncStorage.getItem(AUTH_TOKEN);
            if (!authToken) {
                console.log("Token not set");
            } else {
                this.verifyToken(authToken)
            }
        } catch (error) {
            console.log("Something went wrong");
        }
    }


  async verifyToken(token) {
    let authToken = token

    try {
      let response = await fetch('https://lpfoot.herokuapp.com/api/verify?session%5Bauth_token%5D='+authToken);
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
        //Verified token means user is logged in.

      } else {
          //Handle error
          let error = res;
          throw error;
      }
    } catch(error) {
        console.log("error response: " + error);
    }
  }


render() {
    if (isLogged) {
        return this.props.history.push('./pages/Home');
    } else {
        return this.props.history.push('./pages/Login');
    }


}
}



export default App;

A couple of things are wrong in your code: 您的代码中有几处错误:
trying to call a method getToken outside of the scope where it is defined, here, the class App. 尝试在定义的范围(此处为类App)之外调用方法getToken more about scope . 有关范围的更多信息
Second thing: the render method is called once when the class is instantiated and then if a prop or the local state of the class change. 第二件事:实例化类时,然后如果prop或类的local state发生更改,则一次调用render方法。 In your case changing the value of isLogged won't trigger the render method as isLogged is not part this.props or part of this.state 在你的情况改变的价值isLogged不会触发渲染方法isLogged不是部分this.props或部分this.state

One way you could do this with react would be: 您可以通过react做到这一点的一种方法是:

import React, { Component } from 'react';

import { AsyncStorage } from 'react-native';

import { NativeRouter, Route, Link, Redirect, withRouter } from 'react-router-native'

import Login from './pages/Login';
const AUTH_TOKEN = 'auth_token';

class App extends Component {

    state = {
      isLogged:false
    }

    componentDidMount() {
      this.getToken();
    }

    async getToken() {
        try {
            let authToken = await AsyncStorage.getItem(AUTH_TOKEN);
            if (!authToken) {
                console.log("Token not set");
            } else {
                this.verifyToken(authToken)
            }
        } catch (error) {
            console.log("Something went wrong");
        }
    }

  async verifyToken(token) {
    let authToken = token

    try {
      let response = await fetch('https://lpfoot.herokuapp.com/api/verify?session%5Bauth_token%5D='+authToken);
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
        //Verified token means user is logged in.

        this.setState({ isLogged: true });

      } else {
          //Handle error
          let error = res;
          throw error;
      }
    } catch(error) {
        console.log("error response: " + error);
    }
  }


render() {
    if (this.state.isLogged) {
        return this.props.history.push('./pages/Home');
    } else {
        return this.props.history.push('./pages/Login');
    }
  }
}

export default App;

A couple of things: 有两件事:
About react local state : 关于react local state
- state vs props - 状态与道具
- a good article about understanding setState . - 关于理解setState的好文章
- avoid using componentWillMount but instead componentDidMount more info -避免使用componentWillMount ,而是使用componentDidMount 更多信息

Also render is called everytime a prop or a value of the state is changed, in your case, I guess, you will have issues by pushing to history in a render function. 每当道具或状态值发生更改时,都会调用一次render,我想在您的情况下,通过在render函数中推送到历史记录会遇到问题。 I have not tested it but I would do something like this instead: 我没有测试过,但是我会做这样的事情:

inside async verifyToken(token) 内部async verifyToken(token)

 async verifyToken(token) {
    let authToken = token

    try {
      let response = await fetch('https://lpfoot.herokuapp.com/api/verify?session%5Bauth_token%5D='+authToken);
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
        //Verified token means user is logged in.

        this.props.history.push('./pages/Home');

      } else {
          //Handle error
          let error = res;
          throw error;
      }
    } catch(error) {
        console.log("error response: " + error);
    }
  }

inside of the render method render方法内部

render() {
  <Login />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM