react-redux

React如何与Redux建立联系

主要是2点需求:

  • React组件能在依赖的Store发生变化的时候重新render。
  • React组件能dispatch某个action,从而触发Store更新。

这就需要FB提供的库react-redux了:

  1. 为了提供全局的redux store,需要用到React的context机制。通常将这个context作为app的根节点。
    import React from 'react'
    import ReactDom from 'react-dom'
    import { Provider } from 'react-redux'
    import { store } from './store'
    import App from './app'
     
    const rootEL = document.querySelecor('#root')
    ReactDom.render(
    	<Provider store = {store}>
    		<App />
    	</Provider>,
    	rootEl
    )
  2. 在函数组件中使用react-redux提供的useSelectoruseSelector去获得、更新store:
    import React from 'react'
    import { useSelector, useDispatch } from 'react-redux' 
    export const App = () => {
    	const count = useSelector(state => state.value)
    	const dispatch = useDispatch()
    	return (
    		<div>
    			<button onClick={()=>dispatch({type: 'increament'})}>+</button>
    			<span>{count}</span>
    		</div>
    	)
    }