reference
www.love85g.com/?p=1595
Dependencies that need to be installed
redux react-redux
action
- actionType
export const SET_USER = 'SET_USER'
Copy the code
- action
import * as ACTION_TYPE from './actionType';
export const updateUser = (data) => {
return {
type: ACTION_TYPE.SET_USER,
data
};
};
Copy the code
reducer
import { combineReducers } from 'redux'; import * as ACTION_TYPE from '.. /action/actionType'; Const defaultState = {// initialize state user: {name: 'test ', age: 11}}; function User (state = defaultState, action) { console.log(action); Console. log(state) if (action.type == ACTION_TYPE.SET_USER) {// ES6 three points reference // https://blog.csdn.net/astonishqft/article/details/82899965 // return Object.assign({},state.user,action.user) return {... state.user,... action.data} } return state; }; export default combineReducers({ User });Copy the code
store
import { createStore } from 'redux' import rootReducers from '.. /reducer' let store = createStore(rootReducers) export default storeCopy the code
The entry file is app.js
import 'react-native-gesture-handler';
import * as React from 'react';
import { View } from 'react-native';
import Navigation from './src/index';
import { Provider } from 'react-redux'
import store from './src/redux/store';
const App = () => {
return (
<View style={{flex: 1}}>
<Provider store={store}>
<Navigation />
</Provider>
</View>
);
};
export default App;
Copy the code
use
Reference: / / https://www.cnblogs.com/wuvkcyan/p/10081874.html import React, {Component} from 'React'; import { View, Text, Button } from 'react-native'; import { connect } from 'react-redux'; import { setUser } from '.. /.. /redux/action'; class test extends Component { constructor(props) { super(props); this.state = {}; } test = () => {// get the status console.log(this.props); }; SetTest = (name) => {this.props. UpdateUser ({name: '333',age:223}); }; render() { const ab = 333; Return (<View> <Button title=" View "onPress={this.test} /> <Button style={{padding: OnPress ={this.settest. Bind (this, 'asdfasdFasdfa ')} /> </View>); Const mapState = (state) => ({user: state.user}); Const mapDispatch = (dispatch) => ({updateUser(name) {dispatch(setUser(name)); // The setUser must be the same as the name in the action}}); export default connect(mapState, mapDispatch)(test);Copy the code