文章管理系统——前端(二)

  • 一个后台管理界面的前台
  • 主要技术栈:react hooks + redux + immutable.js + antd
  • 这一章主要讲 redux 结构与 login 的 UI

src 目录改造

1
2
3
4
5
6
7
8
9
10
11
├─api                   // 网路请求代码、工具类函数和相关配置
├─assets // 字体配置及全局样式
├─components // 非路由组件
├─pages // 路由组件
├─routes // 路由配置文件
└─store // redux相关文件
└─utils // 工具模块
App.js // 根组件
index.js // 入口文件
serviceWorker.js // PWA离线应用配置
style.js // 默认样式

重写 App.js

pages 文件夹下创建两个文件夹:loginmain

分别在两个文件夹下创建 index.jsstyle.less,里面写入:

1
2
3
4
5
6
7
8
9
10
import React from 'react';
import { Button } from 'antd';

function Main(){
return(
<Button>Main</Button>
)
}

export default React.memo(Main)

loginindex.js 改一下就行了。

App.js 中导入路由:

1
2
3
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Login from './pages/login';
import Main from './pages/main';

使用路由:

1
2
3
4
5
6
return (
<Router>
<Route path='/login' component={Login}></Route>
<Route path='/' exact component={Main}></Route>
</Router>
);

现在就可以看见效果了。

使用 redux

创建总仓库

urlstore 里面,创建 reducer.jsindex.js,其中reducer.js 代码如下:

1
2
3
4
5
6
// 合并 reducer 函数
import { combineReducers } from 'redux-immutable';

// 合并 reducer 函数为一个 obj
export default combineReducers({
})

这里创建了一个总 reducer,同时我们使用 redux-immutablecombineReducers 来对各组件的 reducer 进行整合。

之后在 index.js 中的代码:

1
2
3
4
5
6
7
8
9
10
11
12

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
))

export default store;

这个代码使用 createStore 创建了总的仓库,使用中间件 thunk,启用了 chrome 的插件 Redux

创建分仓库

pages 文件夹下的 login 文件夹中创建文件夹 store,里面创建四个文件:导出变量的index.js、管理数据的 reducer.js、管理变量的 constants.js、管理 actionactionCreators.js,其中,在 reducer.js 中写入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 获取常量
import * as actionTypes from './constants';
// 导入 immutable 的 frmoJS 方法
import { fromJS } from 'immutable';

// 这里用到fromJS把JS数据结构转化成immutable数据结构
const defaultState = fromJS({
});

export default (state = defaultState, action) => {
switch (action.type) {
default:
return state;
}
}

这就创好了 reducer.js 的基础结构,然后在 index.js 中写入:

1
2
3
4
5
6
7
// 导入仓库
import reducer from './reducer'
// 导入变量
import * as actionCreators from './actionCreators'

// 导出变量
export { reducer, actionCreators };

其他两个文件用时再改。其中 ajax 请求以及后续数据处理的具体代码全部放在 actionCreator 中,由 redux-thunk 进行处理,尽可能精简组件代码。

以后每个需要处理数据的组件都按照上面的结构写。

合并分仓库到总仓库

去修改 src/store/ 下的 reducer.js

1
2
3
4
5
6
7
8
9
// 合并 reducer 函数
import { combineReducers } from 'redux-immutable';
// 导入分仓库的 reducer
import { reducer as loginReducer } from '../pages/login/store';

// 合并 reducer 函数为一个 obj
export default combineReducers({
login: loginReducer
})

这样就把 login 里的数据放进总仓库了,可以在 chromeRedux 查看。

以后每个每一个容器组件都有自己独立的 reducer,然后再全局的 store 下通过 reduxcombineReducer 方法合并。

写 Login 的 UI

1
2
3
4
5
6
{
success:true;
message:"";
data:[{
}]
}
0%