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

How can i do authenticate and navigate to main page in react native?

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

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

当我按下按钮(MyButton)时,我希望代码检查邮件和密码并在正确时重定向到主屏幕(Anaekran.js),但没有任何反应.我找不到问题或问题。我真的很感激你能提供的任何帮助。我会return立即为您解答和提问。

我使用路由器通量进行导航过程。我不分享 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, {Component} from 'react';
import {StyleSheet, Text, 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);

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

<TouchableOpacity
    style={[styles.button, 
    {backgroundColor: this.props.bgColor}]}
    onPress={this.props.onPress}>
    <Text style={{color: this.props.textColor}}>{this.props.text}</Text>
</TouchableOpacity>