或许你当前的项目还没有到应用Redux的程度,但提前了解一下也没有坏处
首先我们会用到哪些框架和工具呢?
React
UI框架
Redux
状态管理工具,与React没有任何关系,其他UI框架也可以使用Redux
react-redux
React插件,作用:方便在React项目中使用Redux
react-thunk
中间件,作用:支持异步action
|--src |-- store Redux目录 |-- actions.js |-- index.js |-- reducers.js |-- state.js |-- components 组件目录 |-- Test.jsx |-- App.js 项目入口
准备工作
第1步:提供默认值,既然用Redux来管理数据,那么数据就一定要有默认值,所以我们将state的默认值统一放置在state.js文件:
// state.js// 声明默认值// 这里我们列举两个示例// 同步数据:pageTitle// 异步数据:infoList(将来用异步接口获取)export default { pageTitle: '首页', infoList: []}
第2步:创建reducer,它就是将来真正要用到的数据,我们将其统一放置在reducers.js文件
// reducers.js// 工具函数,用于组织多个reducer,并返回reducer集合import { combineReducers } from 'redux'// 默认值import defaultState from './state.js'// 一个reducer就是一个函数function pageTitle (state = defaultState.pageTitle, action) { // 不同的action有不同的处理逻辑 switch (action.type) { case 'SET_PAGE_TITLE': return action.data default: return state }}function infoList (state = defaultState.infoList, action) { switch (action.type) { case 'SET_INFO_LIST': return action.data default: return state }}// 导出所有reducerexport default combineReducers({ pageTitle, infoList////
第3步:创建action,现在我们已经创建了reducer,但是还没有对应的action来操作它们,所以接下来就来编写action
// actions.js// action也是函数export function setPageTitle (data) { return (dispatch, getState) => { dispatch({ type: 'SET_PAGE_TITLE', data: data }) }}export function setInfoList (data) { return (dispatch, getState) => { // 使用fetch实现异步请求 window.fetch('/api/getInfoList', { method: 'GET', headers: { 'Content-Type': 'application/json' } }).then(res => { return res.json() }).then(data => { let { code, data } = data if (code === 0) { dispatch({ type: 'SET_INFO_LIST', data: data }) } }) }}
最后一步:创建store实例
// index.js// applyMiddleware: redux通过该函数来使用中间件// createStore: 用于创建store实例import { applyMiddleware, createStore } from 'redux'// 中间件,作用:如果不使用该中间件,当我们dispatch一个action时,需要给dispatch函数传入action对象;但如果我们使用了这个中间件,那么就可以传入一个函数,这个函数接收两个参数:dispatch和getState。这个dispatch可以在将来的异步请求完成后使用,对于异步action很有用import thunk from 'redux-thunk'// 引入reducerimport reducers from './reducers.js'// 创建store实例let store = createStore( reducers, applyMiddleware(thunk))export default store
新闻热点
疑难解答
图片精选