react-redux学习笔记

158 阅读1分钟
  1. redux
  2. redux-devTools
  3. react-redux
  4. redux-thunk

redux

const store = createStore( rootReducer, initialState, enhancer );

store.state保存状态,用store.getState()取出状态;

store.dispatch(action)根据action.type修改状态;

reducer函数根据接收的action.type去执行状态的修改,可拆分reducer对于状态中每一个变量都设定一个小reducer函数;

 

redux-devTools

参考:https://www.jianshu.com/p/a2d4c1856560

需要先在chrome上安装Redux DevTools插件

npm install --save-dev redux-devtools
npm install --save-dev redux-devtools-log-monitor
npm install --save-dev redux-devtools-dock-monitor

 

// DevTools.js

import { createDevTools } from 'redux-devtools';
//显示包是单独的,要额外指定
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';

const DevTools = createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'> <LogMonitor theme='tomorrow' /> </DockMonitor> );

export default DevTools;

// Store.js

import { createStore,compose,applyMiddleware } from 'redux';

const enhancer = compose( //applyMiddleware加上要使用的中间件,没有可省略 applyMiddleware(thunk), DevTools.instrument() );

const store = createStore(rootReducer, initialState, enhancer);

// index.js

import DevTools from "./DevTools.js";
// DevTools必须在Provider里面
ReactDOM.render(
    <Provider store={Store}>
        <CustomComponent/>
        <DevTools/>
    </Provider>,
    document.getElementById('root')
);

使用时如图:

 

 

react-redux

在index.js中用标签<Provider store={store}>包裹子组件,这样子组件不需要import store也能取到store

网上的教程大部分都是用class组件,在class组件中通过this.context.store取出store

在函数组件中需要用到useSelector和useDispatch

useSelector( state => state.var1 ) 相当于 store.getState().var1

const changeStore=useDispatch();  changeStore(action) 相当于 store.dispatch(action)

 

redux-thunk

store.dispatch()参数需要传一个action对象,使用thunk可以传一个函数。

本来传action对象只能同步马上dispatch去修改store,使用thunk传函数后可以在这个函数中可以进行一系列的操作,例如延时dispatch,或者在一次dispatch中发出多个action

使用thunk时需要在createStore时加上applyMiddleware(thunk)引入thunk中间件

原理是在dispatch(action)时拦截检查action是不是function,如果是就调用这个function