ReactNative Hooks

React hooks-> useReducer + useC

2021-04-22  本文已影响0人  精神病患者link常

通过useContextuseReducer中的[state, dispatch]传递下去

⚠️:useReducerredux不一样

步骤

1. 创建全局的rootReducer。多个reducer合并到一起

2. 创建全局的rootContext

3. 根组件使用rootContext .Provider包裹,value传递rootReducer[state, dispatch]

4. 子组件使用const {state,dispatch} = useContext(RootContext)获取全局的数据

1. 创建全局的rootReducer。多个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}
  }
}
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>
...
上一篇下一篇

猜你喜欢

热点阅读