参考
需要安装的依赖
redux react-redux
action
- actionType
export const SET_USER = 'SET_USER'
- action
import * as ACTION_TYPE from './actionType';
export const updateUser = (data) => {
return {
type: ACTION_TYPE.SET_USER,
data
};
};
reducer
import { combineReducers } from 'redux';
import * as ACTION_TYPE from '../action/actionType';
const defaultState = {
// 初始化state
user: {
name: '测试',
age: 11
}
};
function User (state = defaultState, action) {
console.log(action);
console.log(state)
if (action.type == ACTION_TYPE.SET_USER) {
// ES6三个点参考 // 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
});
store
import { createStore } from 'redux'
import rootReducers from '../reducer'
let store = createStore(rootReducers)
export default store
入口文件 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;
使用
// 参考: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 = () => {
//获取状态
console.log(this.props);
};
setTest = (name) => {
//调用方法
this.props.updateUser({ name: '333',age:223 });
};
render() {
const ab = 333;
return (
<View>
<Button title="查看" onPress={this.test} />
<Button
style={{ padding: 20 }}
title="更新state"
onPress={this.setTest.bind(this, 'asdfasdfasdfa')}
/>
</View>
);
}
}
//注册状态
const mapState = (state) => ({
user: state.User
});
//注册方法
const mapDispatch = (dispatch) => ({
updateUser(name) {
dispatch(setUser(name)); //这里需要注意的这个setUser 需要和 action 里的名字一样
}
});
export default connect(mapState, mapDispatch)(test);