React Native Development watercress score (three) Integrated Redux

What is redux

redux is a container for js management application state (state) is. A component such as a change, the component B at the same time to respond. Common application scenario is logged-in user's exit operation: After not logged in, individual centers show the login button, login page to sign in, you need to make the appropriate personal Center page, display personal information. Similar products: vuex, flux, dva, mobx .

redux common into three parts:

  • Action: storage Store ways to change the content, want to change the data inside the Store, which is associated methods Action can only be triggered;
  • Reducer: respond differently to the Action operation, returns a new Store;
  • Store: store data.

Redux in use in this application is mainly used to store user state, home to save data.

React Native redux in use inside

Install its dependencies

yarn add redux redux-persist react-redux
  • redux, react-redux: used to store application state;
  • redux-persist: for off-line storage state, exiting the application into the application again, any of the naturally occurring state.

Edit Action

Create a directory action in the src directory, create index.js directory.

Here create two applications to use the methods, login (login), logout (exit); method 2 test redux whether in effect, add (to increase the numbers), cut (reduce the number).

export function add(num) { // 每个函数的返回值里面必须得有一个type值,Reducer就是根据type值改变做出相应
    return {
        type: 'add',
        value: ++num
    }
}

export function cut(num) {
    return {
        type: 'cut',
        value: --num
    }
}

export function login(data) {
    return {
        type: 'login',
        data
    }
}

export function logout(data) {
    return {
        type: 'logout',
        data
    }
}

Edit Reducer

Create a reducer directory under src directory, create index.js / num.js / user.js directory.

index.js

import { combineReducers } from 'redux';
import num from './num';
import user from './user';

//这里返回的combineReducers()就是 Store 的内容,后面想要获得的话,就是使用 store.user、store.num来获得对应store的数据
export default combineReducers({
    num: num,
    user: user
})

num.js

const initState = {//初始化state内容
    value: 0
}

const setNumState = (state = initState, action) => {
    switch (action.type) {//根据type的不同做出不同的响应
        case 'add':
            return {
                ...state,
                value: action.value,
                status: 'add'
            }
        case 'cut':
            return {
                ...state,
                value: action.value,
                status: 'cut'
            }
        default://必须得有default,用于返回非期望的状态
            return state;
    }
}

export default setNumState;

user.js

const initState = {
    isLogin: false,
    userData: {}
}

const setUserState = (state = initState, action) => {
    switch (action.type) {
        case 'login':
            return {
                ...state,
                isLogin: true,
                userData: action.data
            }
        case 'logout':
            return initState;
        default:
            return state;
    }
}

export default setUserState;

Edit Store

Create a store directory under the src directory, create index.js directory.

import { AsyncStorage } from 'react-native';
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import reducer from '../reducer';

//配置redux-persist,但下次进入应用,就会从root里面获得数据
let persistConfig = {
    key: 'root',
    storage: AsyncStorage,
    stateReconciler: hardSet
}
const persistedReducer = persistReducer(persistConfig, reducer);
export default function configureStore() {
    const store = createStore(persistedReducer);
    let persistor = persistStore(store);
    return { store, persistor };
}

Modify App.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import configureStore from './store';
import Router from './router';

const store = configureStore();

export default class App extends Component {
  render() {
    return (
      <Provider store={store.store} style={{ flex: 1 }}>
        <PersistGate loading={null} persistor={store.persistor}>
          <Router />
        </PersistGate>
      </Provider>
    );
  }
};

Modify pages inside index.js detail.js to test whether the entry into force redux

import React from "react";
import { View, Text } from "react-native";
import { connect } from 'react-redux';
import { add, cut } from '../action';


class Home extends React.Component {
  render() {
    const { dispatch, value, navigation } = this.props;
    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text onPress={() => navigation.push('Detail')}>Home Click Me</Text>
        <View style={{ flexDirection: 'row', width: 300, justifyContent: 'space-around' }}>
          <Text onPress={() => dispatch(add(value))} style={{ backgroundColor: 'blue', color: '#fff', fontSize: 18 }}>减少数字</Text>
          <Text style={{ fontSize: 20 }}>{value}</Text>
          <Text onPress={() => dispatch(cut(value))} style={{ backgroundColor: 'blue', color: '#fff', fontSize: 18 }}>加大数字</Text>
        </View>
      </View>
    );
  }
}

const select = (store) => {
  return {
    value: store.num.value,
  }
}

export default connect(select)(Home);

Renderings:

Here is a basic engineering integrated router, redux, icons of, clone down will be able to use https://github.com/hulinNeil/react-native-base ;

Guess you like

Origin www.cnblogs.com/hl1223/p/11103015.html