如何在React Native中进行身份验证并导航到主页?

我是React Native的新成员,我坚持了:)

我需要使用正确的邮件和密码登录到主屏幕(Anaekran.js)。我从API获取邮件和密码信息。

当我按下按钮(MyButton)时,我希望代码检查邮件和密码并重定向到主屏幕(Anaekran.js)(如果正确),但是什么也没有发生。我找不到问题。我非常感谢您可以提供的任何帮助。我将立即回覆您的答案和问题。

我将路由器流量用于导航过程。我不共享Anaekran.js,因为我不认为我们现在需要Anaekran.js。

某些方法,文件名是土耳其语。

这是LoginSayfasi.js(登录页面)。

import React,{Component} from 'react';
import {View,Alert} from 'react-native';
import Input from '../components/Input';
import MyButton from '../components/MyButton';
import {actions} from 'react-native-router-flux';

import {
    isLogin
} from '../components/Index';

import { serializeKey,setSessionTicket } from '../components/Index'

export default class LoginSayfasi extends Component {
  constructor(props) {
    super(props);
    this.isLoginControl();
    this.state = {
      mail: '',password: '',};
  }
  async isLoginControl() {
        var present = this;
        isLogin().then((res) => {
            if (res)
                actions.Anaekran({type: 'reset'}); 
            else 
                actions.LoginSayfasi({type: 'reset'});
        })
  }
  Giris() {
    var name = this.state.mail;
        var pass = this.state.password;
        if (name == "" || pass == "") {
            Alert.alert("You have to fill ");
        } else {
            fetch('192.168.1.14/rest/signin',{
                method: 'POST',headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',},body: serializeKey({
                    mail: name,password: pass
                })
            })
            .then((res) => res.json()) 
        .then((res) => {
        if (res.session_ticket)
          setSessionTicket(String(res.session_ticket));
            if (res.status != -1)
        actions.Anaekran({type: 'reset'});
            else
                Alert.alert("User could not be verified");
        })
            .catch((err) => {
                Alert.alert("There is a problem here! " + err);
            })
        }
  }
  render() {
    return (
      <View>
        <Input
          placeholder="Mail"
          autoCapitalize="none"
          onSubmitEditing={() => this.passwordInput.focus()}
          onChangeText={(value) => this.setState({mail : value})}
          value={this.state.mail}
          keyboardType={'email-address'}
        />
        <Input
          placeholder="Password"
          secureTextEntry={true}
          inputRef={input => (this.passwordInput = input)}
          onChangeText={(value) => this.setState({password : value})}
          value={this.state.password}
        />
        <MyButton
          textColor={'#f1f1f1'}
          text={'Sign In'}
          bgColor={'#0065e0'}
          onPress={this.Giris.bind(this)}
        />
      </View>
    );
  }
}

Login.js

import React,{Component} from 'react';
import {
  StyleSheet,View,Text,KeyboardAvoidingView
} from 'react-native';
import LoginSayfasi from '../ekranlar/LoginSayfasi';

export default class Login extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.headBackground} />
        <KeyboardAvoidingView behavior={'position'}>
          <View>
            <Text style={styles.text1}>BLA BLA</Text>
            <Text style={styles.text2}>BLAAAA</Text>
          </View>
          <View style={styles.loginArea}>
            <LoginSayfasi />
          </View>
        </KeyboardAvoidingView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
   // STYLES //
});

components / Index.js

import AsyncStorage from '@react-native-community/async-storage';

export function serializeKey(data) {
    var formBody = [];
    for (var property in data) {
      var encodedKey = encodeURIComponent(property);
      var encodedValue = encodeURIComponent(data[property]);
      formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");
    return formBody;
}

export async function isLogin() {
    var session = await AsyncStorage.getItem("session_ticket");
    if (session != null)
        return true;
    return false;
}

export async function setSessionTicket(ticket) {
    AsyncStorage.setItem("session_ticket",ticket);
}

components / Input.js

import React,{Component} from 'react';
import {StyleSheet,TextInput,View} from 'react-native';

export default class Input extends Component {
  state = {
    text: '',};
  render() {
    return (
      <View>
        <TextInput
          {...this.props}
          placeholderTextColor="#ddd"
          style={styles.input}
          value={this.state.text}
          ref={this.props.inputRef}
          onChangeText={text => this.setState({text})}
        />
      </View>
    ); 
  } 
}

const styles = StyleSheet.create({
  // STYLES //
});

components / MyButton.js

import React,TouchableOpacity} from 'react-native';
import PropTypes from 'prop-types';

export default class MyButton extends Component {
  render() {
    return (
      <TouchableOpacity
        style={[styles.button,{backgroundColor: this.props.bgColor}]}>
        <Text style={{color: this.props.textColor}}>{this.props.text}</Text>
      </TouchableOpacity>
    );
  }
}

MyButton.propTypes = {
  text: PropTypes.string.isrequired,bgColor: PropTypes.string,textColor: PropTypes.string,};

const styles = StyleSheet.create({
  // STYLES //
});

package.json

{
  "name": "bookreen","version": "0.0.1","private": true,"scripts": {
    "android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint ."
  },"dependencies": {
    "@react-native-community/async-storage": "^1.7.1","mobx": "^5.15.1","mobx-react": "^6.1.4","react": "16.9.0","react-native": "0.61.5","react-native-gesture-handler": "^1.5.2","react-native-reanimated": "^1.4.0","react-native-router-flux": "^4.0.6","react-native-screens": "^1.0.0-alpha.23","react-navigation": "^4.0.10","react-navigation-stack": "^1.10.3"
  },"devDependencies": {
    "@babel/core": "7.7.5","@babel/plugin-proposal-decorators": "^7.7.4","@babel/runtime": "7.7.6","@react-native-community/eslint-config": "0.0.5","babel-jest": "24.9.0","eslint": "6.7.2","jest": "24.9.0","metro-react-native-babel-preset": "^0.56.3","react-test-renderer": "16.9.0"
  },"jest": {
    "preset": "react-native"
  }
}

App.js(路由)

import React,{ Component } from 'react';
import {
    AppRegistry
} from 'react-native';
import {actions,Scene,Router} from 'react-native-router-flux';

import Anaekran from './ekranlar/Anaekran';
import MahalDetay from './ekranlar/MahalDetay';
import ToplantiList from './ekranlar/ToplantiList';
import Login from './ekranlar/Login';

export default class LoginApp extends Component {

    render() {
        const scenes = actions.create(
          <Scene key="root" hideNavBar={true}>
        <Scene key="Login" component={Login}/>
            <Scene key="Anaekran" component={Anaekran}/>
            <Scene key="MahalDetay" component={MahalDetay}/>
            <Scene key="ToplantiList" component={ToplantiList}/>
          </Scene>
        );

        return <Router scenes={scenes}/>
    }
}

AppRegistry.registerComponent('App',() => App);
wuqingzixiaozi 回答:如何在React Native中进行身份验证并导航到主页?

您正在将onPress属性传递到MyButton组件中,但没有在MyButton.js中处理该属性。这就是为什么您的Giris函数根本没有被执行的原因。您应该在MyButton中处理该属性,并将该属性传递给TouchableOpacity like(注意以onPress开头的行):

<TouchableOpacity
    style={[styles.button,{backgroundColor: this.props.bgColor}]}
    onPress={this.props.onPress}>
    <Text style={{color: this.props.textColor}}>{this.props.text}</Text>
</TouchableOpacity>
本文链接:https://www.f2er.com/2829941.html

大家都在问