【青训营】- React-Redux · 极简教程

372 阅读1分钟

前言:

react-redux 就是为了让 redux 更好的和 react 融为一体. 其核心API 就是 Provide 和 connect, 以及 后来可以 替代 connect 的 react-hooks 方案

1. Provider 优化 store.subsribe

import { useSelector, useDispatch, Provider } from 'react-redux'

/* 不需要store.subscribe, 类似useContext的方式来解决订阅痛点 */

function render() {
  ReactDOM.render(
    <React.StrictMode>
      <Provider store={store} >
        <ReduxPage />
      </Provider>
    </React.StrictMode>,
    document.getElementById('root')
  );
}
render()

// store.subscribe(render)

tips: 如果你对Provider不太了解, 可以尝试先去了解一下 useContext 或者 # 1 分钟带你入门 React Context

2. useSelector, useDispatch 优化 getState, dispatch

const ReduxPage = props => {

  /* 方便使用store.getState 以及 store.dispatch */
  
  // const state = store.getState()
  const state = useSelector(state => state)
  const dispatch = useDispatch()
  return (<>
    <p>{state.todo}</p>
    <p>{state.counter}</p>
    <button onClick={() => {
      // store.dispatch({ type: 'counter/ADD', payload: 2 })
      dispatch({ type: 'counter/ADD', payload: 2 })
    }}>counter add</button>
  </>)
}

Try it at codesandbox