前端

React+Koa服务端渲染(SSR同构),Redux基本配置

2019-08-07聚力创意

// 目录结构

├── store
│   ├── index.js
│   ├── types.js
│   ├── reducer.js
│   ├── actions.js
// index.js

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

const composeEnhancers = composeWithDevTools({})

const getStore = () => createStore(reducer, composeEnhancers(applyMiddleware(thunk)))

const getClientStore = () => {
  const defaultState = window.initialState || {}
  return createStore(reducer, defaultState, composeEnhancers(applyMiddleware(thunk)))
}

export {getStore, getClientStore}
// types.js

const types = {
  SET_SITE_INFO: 'common/SET_SITE_INFO'
}

export default types
// reducer.js

import {combineReducers} from 'redux'
import types from './types'
import homeReducer from '../views/Home/store/reducer'

const defaultState = {
  siteInfo: {},
  categoryList: []
}

const commonReducer = (state = defaultState, action) => {
  switch (action.type) {
    case types.SET_SITE_INFO:
      return Object.assign({}, state, {
        siteInfo: action.siteInfo
      })
    default:
      return state
  }
}

const reducer = combineReducers({
  common: commonReducer,
  home: homeReducer
})

export default reducer
// actions.js

import types from './types'
import {getSiteInfo} from '../api/site'
import {SUCCESS_CODE} from '../config'

export const setInfo = () => (
  async dispatch => {
    try {
      const {code, data} = await getSiteInfo()
      if (code === SUCCESS_CODE) {
        dispatch(SITE_INFO(data))
      }
    } catch (e) {
      console.log(e.message)
    }
  }
)

export const SITE_INFO = siteInfo => ({
  type: types.SET_SITE_INFO,
  siteInfo
})
蜀ICP备17044229号