React|React Native填坑之旅--使用react-redux hooks

React hooks出来之后又打开了一道前端造轮子的大门。各种Hooks的工具满天飞。react-redux也跟上了这波潮流。
项目代码在这里
首先,也是最重要的一点。如果你不知道要不要用redux,那么最好不要用。
【React|React Native填坑之旅--使用react-redux hooks】redux主要解决的问题是统一来源的状态管理。

  1. 全局state存放在store里。store.getState()可以获得state树。
  2. 给store,发送action可以通过reducer生成新的state。store.dispatch({type:SOME_ACTION, data: {})
  3. 订阅store,或者新的state。store.subscribe(() => store.getState())
React-redux主要解决的是第二条。使用connect方法把state和actions都作为props注入到了组件里。
比如现在有一个Counter组件。increment做为action creator。状态就是value++。那么可以写成:
function Counter(props) { // ... return () }const mapStateToProps = (state) => ({ value: state.value, }); const mapActionToProps = (dispatch) => ({ increment: dispatch(increment()), }) connect(mapStateToProps, mapActionToProps)(Counter);

大概就是上面这样的。使用了react-redux的hooks呢,画风一转。整个显得清晰了很多。当然这里也不能少了redux toolkit的帮助。
要实现redux应用的完全体就少不了要创建redux的store等这些前期的配置工作。为了减少这些繁琐的配置,redux开发了toolkit这一套工具。项目代码中都有,可以参考。这里不多介绍。
使用了react-redux之后看起来就是这样了。我们在前期没有多做action(action creator)和reducer的介绍。突然出现不能体现它的简化后的好处。有一点,action和reducer通常都放在不同的地方。使用起来不是十分方便。
在新的实现中这些都在slice文件中,方便统一的管理。维护起来也好很多。
import { createSlice } from '@reduxjs/toolkit'; export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0, }, reducers: { increment: state => { state.value += 1; }, decrement: state => { state.value -= 1; }, incrementByAmount: (state, action) => { state.value += action.payload; }, }, }); // Action creators are generated for each case reducer function export const { increment, decrement, incrementByAmount } = counterSlice.actions;

这是使用了redux toolkit的好处。action的部分基本不用处理。它会自动生成出来action creator。
react-redux的connect方法也省去了。代替的方案是useSelector和useDispatch两个方法。在ReduxCounter组件里:
// ...const ReduxCounter: React.FC = props => { // ... const count = useSelector((state: RootState) => { // 1 return state.counter.value; }); const dispatch = useDispatch(); // 2 const onAdd = () => dispatch(increment()); //3return ( {count} + ); }; export { ReduxCounter };

// 1. 使用useSelector获取state树对应到这个组件的状态
// 2. 使用useDispatch获取dispatch方法,可以发送action
// 3. 在处理add点击的时候调用dispatch方法发送increment() action creator生成的action。

    推荐阅读