【水滴石穿】LoginScreen_Firabase_ReactNativeApp_Redux

先看效果

分析代码我们会发现,它使用了firebase
关于登陆部分应该是实时数据库,应该是他们后端校验的

//app.js
//这里使用了实时数据库
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import firebase from '@firebase/app'
import '@firebase/auth'
import reducers from './reducers';
import LoginForm from './components/LoginForm';
import ReduxThunk from 'redux-thunk';
import Router from './Router';


class App extends Component {

    componentWillMount() {
        const config = {
            apiKey: "AIzaSyCjISFhbzv3O7pYWoF2T9_jAitNz7LuOkI",
            authDomain: "manager-007.firebaseapp.com",
            databaseURL: "https://manager-007.firebaseio.com",
            projectId: "manager-007",
            storageBucket: "manager-007.appspot.com",
            messagingSenderId: "374905155600"
          };
          firebase.initializeApp(config);
    }

    render() {
        const store= createStore(reducers, {}, applyMiddleware(ReduxThunk));
        return (
            <Provider store = {store} >
                <Router/>
            </Provider>
        );
    }
}

export default App;
//router.js
import React from 'react';
import { Scene, Router, Actions } from 'react-native-router-flux';
import LoginForm from './components/LoginForm';
import EmployeeList from './components/EmployeeList'
import EmployeeCreate from './components/EmployeeCreate';

const RouterComponent = () => {
    return(
        <Router>
            <Scene key="root" hideNavBar>
                <Scene key="auth">
                    <Scene key="login" component={LoginForm} title="Login"  initial/>
                </Scene>
                <Scene key="main">
                    <Scene 
                        rightTitle="Add"
                        onRight={() => Actions.employeeCreate() }
                        key="employeeList" 
                        component={EmployeeList} 
                        title="Employees"
                        initial
                        
                    />

                    <Scene 
                        key="employeeCreate" 
                        component={EmployeeCreate} 
                        title="Create Employee"
                    />
                 
                </Scene>
                
            </Scene>
        </Router>

    );
};

export default RouterComponent;
//src/components/LoginForm.js
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, passwordChanged, loginUser } from '../actions';
import { Card, CardSection, Input, Button, Spinner } from './common';




class LoginForm extends Component{

    onEmailChange(text){
        this.props.emailChanged(text);

    }
    onPasswordChange(text){
        this.props.passwordChanged(text);
    }
    onButtonPress(){
        const {email, password } = this.props;
        this.props.loginUser({ email, password});
    }

    renderButton()
    {
        if(this.props.loading)
        {
            return <Spinner size="large"/>
        }
        
        return(
            <Button onPress={this.onButtonPress.bind(this)}>
                Login
            </Button>
        );
            
        
    }

    renderError(){
        if(this.props.error)
        {
            return(
                <View style={{ backgroundColor: 'white'}}>
                    <Text style={styles.errorTextStyle}>
                        {this.props.error}
                    </Text>
                </View>
            );
        }
    }

    render(){
        return (
            <Card>
              
                <CardSection>
                    <Input
                        
                        placeholder="Email"
                        onChangeText={this.onEmailChange.bind(this)}
                        value={this.props.email}
                    />
                </CardSection>

                <CardSection>
                    <Input
                        secureTextEntry
                        
                        placeholder="Password"
                        onChangeText={this.onPasswordChange.bind(this)}
                        value={this.props.password}
                    />
                </CardSection>

                {this.renderError()}

                <CardSection>
                    {this.renderButton()}
                </CardSection>
                
            </Card>
        );
    }
}

const styles = {
    errorTextStyle: {
        fontSize: 20,
        alignSelf: 'center',
        color: 'red'
    }
}

const mapStateToProps = state => {
    return {
        email: state.auth.email,
        password: state.auth.password,
        error : state.auth.error,
        loading : state.auth.loading
    };
};
export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser })( LoginForm);
//src/components/ListItem.js
import React, { Component } from 'react';

import { Text , TouchableWithoutFeedback, View } from 'react-native';
 
import { CardSection } from './common';
import { Actions } from 'react-native-router-flux';

class ListItem extends Component {

    onRowPress() {
        Actions.employeeCreate();
    }
    render() {
        const { name } = this.props.employee;

        return (
            <TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}>
                <View>
                    <CardSection>
                        <Text style ={styles.titleStyle}>
                            {name}
                        </Text>
                    </CardSection>
                </View>
            </TouchableWithoutFeedback>
            
        );
    }
}


const styles = {
    titleStyle:{
        fontSize: 18,
        paddingLeft: 15
    }
}

export default ListItem;
//src/components/EmployeeList.js
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListView} from 'react-native';
import { employeesFetch } from '../actions'
import ListItem from './ListItem';



class EmployeeList extends Component {
    componentWillMount(){
        this.props.employeesFetch();
        this.createDataSource(this.props);

       
    }

    componentWillReceiveProps(nextProps){

        this.createDataSource(nextProps);


    }

    createDataSource({ employees}) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1,r2) => r1 !== r2
        });

        this.dataSource = ds.cloneWithRows(employees);

    }
    renderRow( employee){
        return <ListItem employee = {employee} />
    }


    render() {
        return(
            <ListView
                enableEmptySections
                dataSource={this.dataSource}
                renderRow= {this.renderRow}
            />

        );
    }
}

const mapStateToProps = state => {
    const employees = _.map(state.employees, (val, uid) => {
        return { ...val, uid};
    });

    return { employees };

};

export default connect(mapStateToProps, {employeesFetch}) (EmployeeList);

import React, { Component } from 'react';
import { Picker, Text } from 'react-native';
import { connect } from 'react-redux';
import { employeeUpdate,employeeCreate } from '../actions';
import {Card, CardSection, Input, Button } from './common';


class EmployeeCreate extends Component{
    onButtonPress(){
        const {name, phone, shift } = this.props;
        this.props.employeeCreate({name, phone, shift: shift || 'Monday'});
    }
    render() {
        return(
            <Card>
                <CardSection>
                    <Input
                        label="Name"
                        placeholder="Shajedul"
                        value={this.props.name}
                        onChangeText={text => this.props.employeeUpdate({prop:'name', value: text})}
                    />
                </CardSection>

                <CardSection>
                    <Input
                        label="Phone"
                        placeholder="01628734916"
                        value={this.props.phone}
                        onChangeText={text => this.props.employeeUpdate({prop:'phone', value: text})}
                    />
                </CardSection>
                <Text style={styles.pickerTextStyle}>Shift</Text>
                <CardSection >
                    
                    <Picker
                        style={{ flex: 1 }}
                        selectedValue={this.props.shift}
                        onValueChange={day => this.props.employeeUpdate({prop: 'shift', value: day})}
                    >
                        <Picker.Item label="Monday" value="Monday" />
                        <Picker.Item label="Tuesday" value="Tuesday" />
                        <Picker.Item label="Wednesday" value="Wednesday" />
                        <Picker.Item label="Thursday" value="Thursday" />
                        <Picker.Item label="Friday" value="Friday" />
                        <Picker.Item label="Saturday" value="Saturday" />
                        <Picker.Item label="Sunday" value="Sunday" />
                    </Picker>
                </CardSection>

               

                <CardSection>
                    <Button onPress={this.onButtonPress.bind(this)}>
                        Create
                    </Button>
                </CardSection>
            </Card>
        );
    }
}

const styles = {
    pickerTextStyle: {
        fontSize: 18,
        paddingLeft: 18,
        paddingTop: 5,
        paddingBottom: 5
        
    }
}

const mapStateToProps = (state) => {
    const { name, phone, shift } = state.employeeForm;
    return { name, phone, shift };
};

export default connect(mapStateToProps, { employeeUpdate, employeeCreate }) (EmployeeCreate);

在action中的处理

import firebase from '@firebase/app';
import '@firebase/auth'
import '@firebase/database'
import { Actions } from 'react-native-router-flux';
import {
    EMPLOYEE_UPDATE,
    EMPLOYEE_CREATE,
    EMPLOYEES_FETCH_SUCCESS
} from './types';


export const employeeUpdate = ({ prop, value }) => {
    return {
        type: EMPLOYEE_UPDATE,
        payload: {prop, value}
    };

};

export const employeeCreate = ({ name, phone, shift }) => {
    const { currentUser } = firebase.auth();

    return(dispatch) => 
    {

        firebase.database().ref(`/users/${currentUser.uid}/employees`)
            .push({ name, phone, shift })
            .then(() => 
            {
                dispatch({ type: EMPLOYEE_CREATE});
                Actions.pop();
            });
    };


};

export const employeesFetch = () =>{
    const { currentUser } = firebase.auth();
    return(dispatch) => {
        firebase.database().ref(`/users/${currentUser.uid}/employees`)
            .on('value', snapshot => {
                dispatch({ type: EMPLOYEES_FETCH_SUCCESS, payload: snapshot.val() });
            });
    };
};

用的redux还是有些复杂啊~
项目地址:https://github.com/shajedulislam/LoginScreen_Firabase_ReactNativeApp_Redux

posted @ 2019-05-16 16:04  jser_dimple  阅读(176)  评论(0编辑  收藏  举报
/*function gotourl() { var url = "https://www.cnblogs.com/smart-girl/"; var localurl = document.url; if( localurl.substring(0,url.length) != url ) { location.href=url; } } gotourl();*/