在React项目中使用redux

前言: 此博文是记录我在b站上观看redux教学视频的记录
原视频链接在此 react-redux看这个视频就够了!

一、安装相关的插件

1、安装 redux
npm install -S redux
2、安装 redux-thunk
npm install -S redux-thunk
3、在 chrome 应用商店安装 redux-devtools

二、引入相关插件

import {createStore, combineReducers, compose, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'

三、创建 Reducer

const counterReducer = function(state = {count: 1}, action) {
  switch(action.type){
    case 'COUNT_ADD':
      return {
        count: state.count + 2
      }
    case 'COUNT_REDUCE':
      return {
        count: state.count - 1
      }
    default: 
    return state
  }
}

const postReducer = function (state = {list: [{title: '你好'}]}, action) {
  switch (action.type) {
    case 'LOAD_POST':
      return {
        ...state, list: action.payload
      }
    default: 
      return state
  }
}

四、合并 Reducer

const rootReducer = combineReducers({
  counter: counterReducer,
  post: postReducer
})

五、创建 store

const store = createStore(
  rootReducer,
  compose(
    applyMiddleware(...[thunk]),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
)

// window 那一行是用来配置浏览器启动 redux-devtools 的
// applyMiddleware 是启用 redux-thunk 中间件

六、使用 getState() 获取状态

store.getState()

七、使用 dispatch() 修改状态

store.dispatch({
  type: 'COUNT_ADD',
  payload: {},
})

store.dispatch({
  type: 'COUNT_REDUCE',
  payload: {},
})

const getPostRequest = () => {
  return axios.get('https://jsonplaceholder.typicode.com/posts')
}

store.dispatch(async function (dispatch) {
  const res = await getPostRequest()
  console.log(res.data)
  dispatch({
    type: 'LOAD_POST',
    payload: res.data
  })
})

你可能感兴趣的:(在React项目中使用redux)