Redux 笔记(1) --- Redux 基本工作流程

108 阅读1分钟

首先在React component里面的某一个function中声明一个 action,这个function可以是constructor, componentDidMount, componentWillMount或者是handleClick之类的,取决于你想实现的功能,例如:

constructor() {
  super();

  this.state = store.getState()
)

const action = {
   type: "GET_PIZZA_ITEMS"
   ...
}

这个action的作用就是相当于React Component发送的一条指令,说出的一句话,我们同时可以在这里面传递一些数据,接下来我们要用dispatch对这个action进行操作:

store.dispatch(action)

接下来我们需要对store进行构建:./store/index.js

import { createStore, applyMiddleWare } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducer from '../reducer';

const middleWare = [ thunk ];

const store = createStore(
    reducer,
    composeWithDevTools(applyMiddleWare(...middleware)),
);

export default store;

这里就存在几个问题需要说明:

  • Redux中的 createStore 和 applyMiddleWare 应该怎么使用
  • thunk的作用是什么
  • redux-dev-tools应该怎么使用

因为这节笔记主要记录redux的流程,会在接下来的笔记中进行补充

接下来我们注意到 引用了一个reducer,我们需要构建一个reducer, ./reducer/index.js

const defaultState = {
   name: "Peri Peri",
   price: 15
}

const sampleReducer = ( state = defaultState, action ) => {
    const newState = JSON.parse(JSON.stringify(state));

    switch(action.type) {
       case: "GET_PIZZA_ITEM":
          return newState

       default:
          return
    }
}

module.export = sampleReducer

这里我们需要注意redux是不允许对于defaultState进行直接操作的 

最后我们需要将newState返回给 react component

store.subscribe(this.handleStoreChange)

handleStoreChange = () => {
  this.setState(store.getState())
}

这样我们就可以把component内的state转移到reducer当中了