React hooks进去之后又关上了一道前端造轮子的大门。各种Hooks的工具满天飞。react-redux也跟上了这波潮流。
我的项目代码在这里
首先,也是最重要的一点。如果你不晓得要不要用redux,那么最好不要用。
redux次要解决的问题是对立起源的状态治理。
- 全局state寄存在store里。
store.getState()
能够取得state树。 - 给store,发送action能够通过reducer生成新的state。
store.dispatch({type:SOME_ACTION, data: {})
。 - 订阅store,或者新的state。
store.subscribe(() => store.getState())
。
React-redux次要解决的是第二条。应用connect
办法把state和actions都作为props注入到了组件里。
比方当初有一个Counter
组件。increment做为action creator。状态就是value++。那么能够写成:
function Counter(props) { // ... return (<Button onClick={() => props.increment()}>+</Button>)}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 functionexport const { increment, decrement, incrementByAmount } = counterSlice.actions;
这是应用了redux toolkit的益处。action的局部根本不必解决。它会主动生成进去action creator。
react-redux的connect办法也省去了。代替的计划是useSelector和useDispatch两个办法。在ReduxCounter组件里:
// ...const ReduxCounter: React.FC<ReduxCounterProps> = props => { // ... const count = useSelector((state: RootState) => { // 1 return state.counter.value; }); const dispatch = useDispatch(); // 2 const onAdd = () => dispatch(increment()); //3 return ( <View> <Text>{count}</Text> </View> <View style={styles.buttonWrapper}> <TouchableHighlight style={styles.button} onPress={onAdd}> <View style={styles.buttonInsider}> <Text>+</Text> </View> </TouchableHighlight> );};export { ReduxCounter };
// 1. 应用useSelector
获取state树对应到这个组件的状态
// 2. 应用useDispatch
获取dispatch办法,能够发送action
// 3. 在解决add点击的时候调用dispatch办法发送increment()
action creator生成的action。