1.下载依赖,这里是以rn为例子,路由组件不在本次叙说之内
npm install react-redux --save
npm isntall redux --save
npm install redux-thunk
2.定义1个全局reduxStore
// 这个是让数据生效,和结合谷歌插件的代码
export const reduxStore = createStore(
counter,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f,
),
);
const App = () => {
return (
<View style={[styles.content]}>
<Provider store={reduxStore}>
<Navigation />
</Provider>
</View>
);
};
3.传统的获取数据和方法的方式
注意
connect 第一个参数:获取redux里面的数据 第二个参数获取redux里面的方法,每一次都需要引入对应的高阶函数来包裹
import {View, Button, Text} from 'react-native';
import {connect} from 'react-redux';
import {addDelAsync} from '../../redux/store/index.redux';
const HomeScreen = ({navigation, conut, addDelAsync}) => {
const add = () => {
addDelAsync();
};
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Button
title="Go to Details1"
onPress={() => navigation.navigate('Details')}
/>
<Button title="add" onPress={() => add()} />
<Text>{conut}</Text>
<Button title="del" onPress={() => navigation.navigate('Details')} />
</View>
);
};
const mapStateToProps = state => {
console.log('redux-State 数据获取方式...', state);
return {
conut: state.home.conut,
};
};
// 获得方法,方法是上面倒入的 //将action的所有方法绑定到props上
const mapDispatchToProps = {addDelAsync};
// connect 第一个是获得数据源,第二个是获得方法源
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
4.hooks结合redux使用的方式 useSelector, useDispatch
对connect高阶组件
做了功能拆分
const num =
useSelector(state => state.home.conut)
获取对应的redux数据
const dispatch = useDispatch()
;
1.dispatch({type: 'ADD_DEL'}); 间接提交type类型,可以不引入函数
2.dispatch(addDelAsync()); 直接执行方法,还是需要引入对应的方法
但是都不会引入connect来多次深层次的包裹,从代码量和按需引入做的更加彻底!
import {useSelector, useDispatch} from 'react-redux';
import {addDelAsync} from '../../redux/store/index.redux';
const SettingsScreen = ({navigation}) => {
const num = useSelector(state => state.home.conut);
const dispatch = useDispatch();
const addNumber = () => {
// dispatch({type: 'ADD_DEL'});
dispatch(addDelAsync());
};
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Button
onPress={() => {
addNumber();
}}
title="add"
/>
<Text>{num}SettingsSettingsSettingsSettings</Text>
<Button
title="navigationnavigation"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
};
export default SettingsScreen;