1.0.3 • Published 3 years ago

@maple-rc/redux-hook v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

redux-hook

npm version Build Status

Use hooks realize redux in react


安装

    yarn add @maple-rc/redux-hook

使用

Provider

容器,传入 reducerinitState,生成全局 Store

用法

<Provider reducer={reducer} initState={initState}>
  {children}
</Provider>

入参

参数说明类型
reducerreducer值object
initState初始stateobject

示例

import Demo from './demo/index'
import { Provider, combineReducers } from './hooks'

import { reducers, initState } from './demo/reduces'

const App = () => {
  const combinedReducer = combineReducers(reducers)
  return (
    <Provider reducer={combinedReducer} initState={initState}>
      <Demo />
    </Provider>
  )
}

export default App

combineReducers

将拆分的多个 reducer,合并一个最终的 reducer

用法

combineReducers(reducers)

入参

参数说明类型
reducersreducer键值对object

示例

const reducers = {
  todos: (state: ITodos, action: IAction) => {
    switch (action.type) {
      case 'CHANGE_TEXT':
        return {
          ...state,
          text: action.payload,
        }
      default:
        return state
    }
  },
  counter: (state: ICounter, action: IAction) => {
    switch (action.type) {
      case 'CHANGE_COUNT':
        return {
          ...state,
          count: action.payload,
        }
      default:
        return state
    }
  }
}

combineReducers(reducers)
// 最终的 reducer 伪代码
(state: Object = {}, action: IAction) => {
  switch (action.type) {
    case 'CHANGE_TEXT':
      return {
        ...state,
        text: action.payload,
      }
    case 'CHANGE_COUNT':
      return {
        ...state,
        count: action.payload,
      }
    default:
      return state
  }
}

connect

连接页面与 Store,切分并注入 Store state

用法

connect([selecter], [mergeProps])

入参

参数说明类型
selecterStore state 切分函数func
mergeProps组合 Store statepropsfunc

示例

import { Dispatch } from 'react'
import connect from '../hooks/connect'
import { IAction, IState } from '../hooks/types'
import * as actions from './actions'

interface IProps {
  todos: {
    text: string
  }
  counter: {
    count: number
  }
  dispatch: Dispatch<IAction>
}

const Todos = (props: IProps) => {
  // 用 useContext 来获取 state 与 dispatch
  const { todos, counter, dispatch } = props
  const change = (val: string) => dispatch(actions.changeText(val))
  const increment = () => dispatch(actions.increment(counter.count))
  console.log('todos', todos)

  return (
    <div>
      <h1>The text is {todos.text}</h1>
      <button onClick={() => change('new')}>change</button>
      <button onClick={increment}>increment</button>
    </div>
  )
}

export default connect(
  (state: IState) => state.counter, // selector
  (state: IState) => state.todos, // selector
  (counter: IState, todos: IState) => ({ counter, todos }) // mergeProps
)(Todos)

useDispatch

获取 dispatch

用法

useDispatch()

回参

参数说明类型
useDispatchdispatch 函数func