Shallow into react-native using Redux_redux

Source: Internet
Author: User


Redux is a JavaScript state container that provides predictable state management.



Beginners this, feel that some articles on the internet is not so easy to understand, here in simple words to introduce the use of redux in react-native.



Plainly on the three main things, Action,store and reducer.




Action: Mainly used to trigger a number of transactions to change state, usually with setstate change.
REDUCER: After the action is triggered, the action is processed and a new state is returned.



Store: Each program has and only one store, as a root node to manage the state, many state equals child nodes. Action and reduce are connected through the store.






Let's take a direct example and compare the difference between state by traditional SetState method and using Redux



Let's start with the redux environment.



NPM Install--save Redux "redux package"



NPM install--save React-redux "React-redux is the package that Redux needs to rely on"



NPM install--save redux-thunk "Redux-thunk is used to allow Redux to have an asynchronous action transaction"






First look at the project directory structure, there are three folders, is the above three things ...






Store left in the last to say because this is the other two connected objects.






The flow of these three things is like this,



1.Store Needless to say, it's all about copying a code. Then tie the store to the properties of the root page.



2.Reducer, build an indexed file as a binding reducer (also a copy of Kung Fu), and then you can write multiple reducer. Reducer is the action that is distributed through the action, and the logical code that finds the appropriate type of reducer,reducer generates a new state, which is then sent back to the store.



3.Action, to trigger the page, when the page is bound to connect, you can get the "dispatch distributor" and "store management state" through props, dispatch distributor on the page: (1) The event will be passed to Action. (2) The action is then distributed to the Reducer in dispatch. (3) Reducer has bound the store, as long as return a state to Store,store will replace the new state old.



4. From the above three steps can be seen, the operation of these three things flow, but will be a little fuzzy, I see a lot of stickers will have this question, I am now very familiar with the principle of redux, how do I unified management state it. Looking back at the 1th, the store is tied to the root page, so we can get store-managed state. To recap the 2nd, Reducer requires an index to bind multiple reducer, so the new state that each reducer returns is bound to the index. Finally, in the 3rd, the page gets the state of store management. Combined with the above analysis, according to the Reducer index can find the corresponding state, and then let the page to get the corresponding state.



Redux in fact, more than directly with the traditional state is a lot of trouble, because write a lot of code to achieve the use of traditional state effect. But the maintenance of this is critical, unified management State, in the maintenance, absolutely faster than the traditional state, because there are business logic code changes, do not open that bloated interface slowly looking, in the Redux framework can quickly find the appropriate code, and see the code is concise. This is probably the upfront cost so much strength also want to use Redux reason.






First action,



Loginaction.js is a login action, which is written very simply to see if the account password is correct.





Import * as types from './actiontype ';

Export function performloginaction (username, password) {return
	(Dispatch) => {
		console.log ("Run ..... Performloginaction.....performlogin ");
		Dispatch (Performlogin ());
		if (username = = ' Ljy ' && password = = ' 123 ') {
			dispatch (Receiveloginresult ("succeed"));
		} else {
			/ Dispatch (Receiveloginresult ("fail"));
			Dispatch (Receiveloginresult ("fail"));

}} function Performlogin () {return
	{
		type:types. Perform_login_action,
	}
function Receiveloginresult (result) {return
	{
		type:types. Receive_login_action,
		data:result
	}
}





The actiontype.js above is the following paragraph you are not mistaken, this file is mainly used to write some action type, why do you need this? Because our usual management of RN data, are used state management, this redux as a middleware unified management of all State, so there is an action type, so that the action can be correctly distributed to the next level reducer.





Export Const Perform_login_action = ' perform_login_action ';
Export Const Receive_login_action = ' receive_login_action ';

Not to mention the function call, first of all to understand the role of each function, later used to mention.





Performloginaction (username, password) This method is used to process the login, the inside return a method, you can see that the method has multiple dispatch methods. Dispatch is used to pass to the next level. The next level of action is reducer, visible performloginaction (username, password) method below There are two ways to return an object, which is to pass the object to the reducer. The biggest question is (dispatch) =>{} brackets in the dispatch from where, the above process 3rd, the page binding data connect can get dispatch, the dispatch of the action here is of course from the page passed over.






Come again, reducer.



Need an index, build a index.js, the code is a copy, to change is combinereducers inside objects, such as login is index (key), object is the introduction of the Loginreducers.





Import {combinereducers} from ' Redux ';
Import loginreducers from './loginreducers ';
Import LoginReducers2 from './loginreducers2 ';

Const Rootreducer = combinereducers ({
	login:loginreducers,
	login2:loginreducers2
});

Export default rootreducer;
There are two reducer from the index, one of the loginreducers.js is given here, the other is very similar.







Import * as types from '. /action/actiontype ';

Const Initialstate = {
	loading:false,
	data: ',
}

export default function login (state = Initialstate, Action {
	switch (action.type) {case
		types. Perform_login_action: Return
			{
				... state,
				loading:true,
			};
		Case types. Receive_login_action: Return
			{
				... state,
				loading:false,
				data:action.data
			};
		Default: Return state
			;
	}


The dispatch in the action is passed to reducer, where the action dispatch has only one argument, which is passed to the reducer's provided action parameter of the login method, because the first argument is the built-in state parameter. Here the login method has a switch that returns the corresponding state according to the action type, otherwise it returns the original state.



This paragraph is to rely on JS Foundation, should be able to understand?... state is a grammar, meaning the state of all the key values to the list, such as: Loading:false,data: "",






To the store again,



Configure-store.js, most of them copy, this may be different from the traditional redux, because the use of redux-thunk, the role of the above mentioned.





Import {createstore, applymiddleware} from ' Redux ';
Import thunkmiddleware from ' Redux-thunk ';
Import Rootreducer from '. /reducers/index ';

Const Createstorewithmiddleware = Applymiddleware (thunkmiddleware) (createstore);

Export default function Configurestore (initialstate) {
	Const store = Createstorewithmiddleware (Rootreducer, initialstate);
	return store;
}

It says Reducer's index file, which is used here, is connected to the store. The imported rootreducer is the index we have written above.








Successful half, understand the redux aspects of the principle, combined with the above code, redux this piece is simple to get started. What else has not been done. Write a good Redux section, on the page is called.






Finally to page,



Page root directory root.js, with React-redux provider bind store. is still a copy, the role is to import the store bound to the interface.





Import react, {Component} from ' React ';
import{} from ' react-native ';

Import {Provider} from ' React-redux '
import configurestore from './store/configure-store '

import App from '. APP '

Const store = Configurestore ();

Export default class Rootapp extends Component {

	render () {return
		(
			<provider store={store}>
				<app/>
			</provider >
		)
	}
}

The root directory is ready to be used on subpages after it has been bundled with the store. Here the component of the sub-page, you need to use the React-redux provided by the Connect export. The following explains the binding data to the child page in detail.





To better contrast SetState and dispatch two ways to change state, the code for the following TextInput control uses dispatch for the code of the Setstate,touchableopacity control.






Provider contains the root page, app.js





import React, {Component} from 'react';
import {
	AppRegistry,
	StyleSheet,
	Text,
	View,
	TouchableOpacity,
	TextInput
} from 'react-native'
import {connect} from 'react-redux';
import {performLoginAction} from './action/LoginAction';

class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			username: '',
			psw: ''
		};
	}

	render() {
		const {dispatch, login} = this.props;
		return (
			<View style={{flex: 1, justifyContent: 'center'}}>
				<View style={{height: 100, margin: 10}}>
					<View style={{flex: 1}}>
						<TextInput
							style={{fontSize: 20}}
							underlineColorAndroid={'transparent'}
							placeholder={"帐号"}
							onChangeText={(username) => this.setState({username})}
							value={this.state.username}
						/>
					</View>
					<View style={{height: 1, backgroundColor: '#eee'}}/>
					<View style={{flex: 1}}>
						<TextInput
							style={{fontSize: 20}}
							underlineColorAndroid={'transparent'}
							placeholder={"密码"}
							onChangeText={(psw) => this.setState({psw})}
							value={this.state.psw}
						/>
					</View>
					<View style={{height: 1, backgroundColor: '#eee'}}/>
				</View>
				<View style={{margin: 10, alignItems: 'center'}}>
					<TouchableOpacity onPress={()=> {
						dispatch(performLoginAction(this.state.username, this.state.psw));
					}}>
						<Text style={{fontSize: 30}}>登录</Text>
					</TouchableOpacity>
				</View>
				<View style={{height: 100, margin: 10, justifyContent: 'center', alignItems: 'center'}}>
					<Text style={{height: 30, fontSize: 20, margin: 10}}>{login.data}</Text>
				</View>
			</View>
		)
			;
	}
}
function mapStateToProps(state) {
	const {login} = state;
	return {
		login
	}
}
export default connect(mapStateToProps)(App);









The last line of Connect is in the sub page or the control bar, to bind data to the store. Connect requires a Mapstatetoprops method to return a Reducer,mapstatetoprops method has a parameter state, this is the store unified management of the State, that is, the root node. There is a reducer index is login, learning JS This sentence should be read, const {LOGIN} = state; equals const LOGIN = State.login;



Feel a little bit ... Reducer's index is used to differentiate each state, but the store is a root node that unifies all the state of the index to a single root node.





function Mapstatetoprops (state) {
	const {LOGIN} = state;
	return {
		login
	}
}
export default connect (mapstatetoprops) (APP);






With Connect this step,



This page or the control, the props property has something to take. Can get dispatch, this distributor is too familiar with the above mentioned rotten ... There is also a login, where this login came from. The Mapstatetoprops method returns the index of login Reducer,reducer is the return state, so there is this argument login, essentially a state. The state of the page here is that Login,login is read-only and cannot be written, and cannot be changed with SetState, to be distributed to action,action (not state) to Reducer with dispatch distribution events (not state). Reducer returns state to Store,store to replace the corresponding index with the new state.





const {dispatch, login} = this.props;

Get state, is read only, direct use is good, the usual setstate habit change to dispatch write. The redux is getting started.








Briefly introduced react-native used a bit of redux. Related source Baidu Search, a lot of ...

















Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.