React hooks-> useReducer + useC
2021-04-22 本文已影响0人
精神病患者link常
通过useContext
将useReducer
中的[state, dispatch]
传递下去
⚠️:useReducer
和redux
不一样
步骤
1. 创建全局的
rootReducer
。多个reducer
合并到一起2. 创建全局的
rootContext
。3. 根组件使用
rootContext .Provider
包裹,value传递rootReducer
的[state, dispatch]
4. 子组件使用
const {state,dispatch} = useContext(RootContext)
获取全局的数据
1. 创建全局的rootReducer
。多个reducer
合并到一起
- 创建两个
reducer
export const userInitState = {
userName:'张三',
userAge:20,
userSex:0,
userPhone:'15111111111'
}
export const useReducer=(state, action)=>{
switch(action.type){
case 'changeName':
return {
...state,
userName:action.name
}
case 'changeAge':
return {
...state,
userAge:action.age
}
default:
return {...state}
}
}
export const appInitState = {
version:'0.0.1',
appName:'test'
}
export const appReducer=(state, action)=>{
switch(action.type){
case 'changeName':
return {
...state,
appName:action.name
}
case 'changeVersion':
return {
...state,
version:action.version
}
default:
return {...state}
}
}
- 创建
rootReducer
,进行合并
import {useReducer, userInitState} from './userReduce'
import {appReducer, appInitState} from './appReduce'
export const rootInitState = {
userReduce:userInitState,
appReduce:appInitState
}
export const rootReduce = (state, action)=>{
return {
userReduce:useReducer(state.userReduce,action), // 注意此处传入的数据 state.userReduce 不是 state
appReduce:appReducer(state.appReduce,action)
}
}
2. 创建全局的rootContext
import { createContext } from 'react'
export const RootContext = createContext(null)
3. 根组件使用rootContext .Provider
包裹,value传递rootReducer
的[state, dispatch]
- 根组件
import { rootReduce, rootInitState } from './src/reduce/rootReduce'
import { RootContext } from './src/reduce/rootContext'
function StackNavigator() {
const [state, dispatch] = React.useReducer(rootReduce, rootInitState)
return <RootContext.Provider value={{state,dispatch}}>
...
</RootContext.Provider>
}
4. 子组件使用const {state,dispatch} = useContext(RootContext)
获取全局的数据
const {state,dispatch} = useContext(RootContext) // 获取全局的数据
return (
<View style={[styles.mainView,{backgroundColor:themesContent.color}]}>
<Text>{state.userReduce.userName} {state.userReduce.userAge}岁</Text>
<TouchableOpacity onPress={()=>{
dispatch({type:'changeAge',age:21})
}}>
<Text>点击修改用户的年龄</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>{
dispatch({type:'changeName',name:'李四'})
}}>
<Text>点击修改用户的名字</Text>
</TouchableOpacity>
...