如何在React Native中使用JSON提取进行登录身份验证?

时间:2020-02-12 12:32:51

标签: react-native authentication

我需要做一个登录身份验证,以响应本机来获取像下面这样的JSON文件中的用户:

  async componentDidMount() {
    return fetch(
'https://gist.githubusercontent.com/MatheusCbrl/9504064f6605726886df412681fca376/raw/77666e642ee610cfab0aa690d543b3be2c07ba4e/teste.json'
    )
      .then(response => response.json())
      .then(responseJson => {
        // just setState here e.g.
        this.setState({
          users: responseJson,
        });
      })
      .catch(error => {
        console.error(error);
      });
  }

我试图做这样的事情:

  _signin = async () => {
    const{username, password} = this.state
    if(username == ""){
      Alert.alert(" ",'Por favor digite a Matrícula')

    } else if(password == ""){
      Alert.alert(" ",'Por favor digite o seu RG')

    } else if (
      username.response === this.state.username &&
      password.response === this.state.password
    ) {
      await AsyncStorage.setItem('Logado', '1');
      this.props.navigation.navigate('Diurno');
      console.log('entrou')
    } else {
     this.setState({ isVisible: true })
      console.log('login inválido');
    }

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

首先不是一个好的做法,将生命周期函数设为异步,则应创建另一个异步函数并在didMount上调用它。

state = {
  users: []
}

componentDidMount() {
  fetchData()
}

componentDidUpdate(prevState) {
   if (prevState.users.length > 0 && (prevState.users !== this.state.users)) {
      singIn()
   }
}

function fetchData() {
    const url = 'https://gist.githubusercontent.com/MatheusCbrl/9504064f6605726886df412681fca376/raw/77666e642ee610cfab0aa690d543b3be2c07ba4e/teste.json'
    fetch(url)
        .then(response => response.json())
        .then(data => {
            this.setState({ users: data})

         })
    .catch(error => console.log('oops run to the hills!!!!', error))
}

function signIn() {
    const [findUser] = this.state.users.filter(user => user.cpf === 'whatever')
    if(findUser) {
        //login
    } else {
        //invalid login
 }
}