Using Redux on react native (I) — adding Redux

Time:2021-12-2

Original project

This is a very simple project, which is a counter with only two filespackage.jsonandindex.ios.js, clickPlus 1The digital value of the button will be + 1, clickMinus 1The numeric value of the button will be – 1, clickReturn to zeroButton, the digital value is set to 0;

index.ios.jscode:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 5 }
  }

  _onPressReset() {
    this.setState({ count: 0 })
  }

  _onPressInc() {
    this.setState({ count: this.state.count+1 });
  }

  _onPressDec() {
    this.setState({ count: this.state.count-1 });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.state.count}</Text>
        <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}>
          < text > return to zero < / text >
        </TouchableOpacity>
        <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}>
          < text > plus 1 < / text >
        </TouchableOpacity>
        <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}>
          < text > minus 1 < / text >
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'column'
  },
  counter: {
    fontSize: 50,
    marginBottom: 70
  },
  reset: {
    margin: 10,
    backgroundColor: 'yellow'
  },
  start: {
    margin: 10,
    backgroundColor: 'yellow'
  },
  stop: {
    margin: 10,
    backgroundColor: 'yellow'
  }
})

AppRegistry.registerComponent('Helloworld', () => Main);

Add Redux

Add firstreduxRelated dependency libraries, inpackage.jsonAdd three libraries to the directorynpm install:

"dependencies": {
    ...
    "react-redux": "^4.4.5",
    "redux": "^3.5.2",
    "redux-logger": "^2.6.1"
},

RecreateactionsTypes.jsUsed to define allactionName, define threeaction, one increase, one decrease, one reset:

export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
export const RESET = 'RESET';

establishactions.js, create three in itaction:

import { INCREASE, DECREASE, RESET } from './actionsTypes';

const increase = () => ({ type: INCREASE });
const decrease = () => ({ type: DECREASE });
const reset = () => ({ type: RESET });

export {
    increase,
    decrease,
    reset
}

establishreducers.js, upon receipt of relevantactionWhen operating itemsstate:

import { combineReducers } from 'redux';
import { INCREASE, DECREASE, RESET} from './actionsTypes';

//Original default state
const defaultState = {
  count: 5,
  factor: 1
}

function counter(state = defaultState, action) {
  switch (action.type) {
    case INCREASE:
      return { ...state, count: state.count + state.factor };
    case DECREASE:
      return { ...state, count: state.count - state.factor };
    case RESET:
      return { ...state, count: 0 };
    default:
      return state;
  }
}

export default combineReducers({
    counter
});

establishstore.js:

import { createStore, applyMiddleware, compose } from 'redux';
import createLogger from 'redux-logger';
import rootReducer from './reducers';

const configureStore = preloadedState => {
    return createStore (
        rootReducer,
        preloadedState,
        compose (
            applyMiddleware(createLogger)
        )
    );
}

const store = configureStore();

export default store;

thusreduxMost of are created. The next step is to introduce them into the projectapp.jsandhome.js.

Index.ios.js change:

import { AppRegistry } from 'react-native';
import App from './app';

AppRegistry.registerComponent('Helloworld', () => App);

app.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Home from './home';
import store from './store';

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Home/>
      </Provider>
    );
  }
}

Home.js in the originalindex.ios.jsThe code is modified as follows:

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { connect } from 'react-redux';
import { increase, decrease, reset } from './actions';

class Home extends Component {
  _onPressReset() {
    this.props.dispatch(reset());
  }

  _onPressInc() {
    this.props.dispatch(increase());
  }

  _onPressDec() {
    this.props.dispatch(decrease());
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.counter}>{this.props.counter.count}</Text>
        <TouchableOpacity style={styles.reset} onPress={()=>this._onPressReset()}>
          < text > return to zero < / text >
        </TouchableOpacity>
        <TouchableOpacity style={styles.start} onPress={()=>this._onPressInc()}>
          < text > plus 1 < / text >
        </TouchableOpacity>
        <TouchableOpacity style={styles.stop} onPress={()=>this._onPressDec()}>
          < text > minus 1 < / text >
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  ...
})

const mapStateToProps = state => ({
    counter: state.counter
})

export default connect(mapStateToProps)(Home);

OK, it’s done,commond+Rfunction,command+DopenchromeBrowser debugging, you can seeredux-loggerPut eachactionAll the movements are in harmonystateThe changes before and after are printed, which is very intuitive and convenient

Using Redux on react native (I) -- adding Redux