1.安装create-react-app
npm install create-app -g (-g 全局安装)
2.为项目命名
create-react-app demo-project (demo-project为项目名称)
3.一个可运行的项目就安装好了,可以运行了(默认端口3000)
npm run start
4.如果要暴露所有配置 使用npm run eject,项目目录如下:
5.安装dva库,通过 reducers, effects 和 subscriptions 组织 model,简化 redux 和 redux-saga 引入的概念(dva官方:https://dvajs.com/)
npm install dva --save
6.改造项目为dva模式(不了解dva的同学可网上自行学习),在src目录下新建目录:models,services,routes,utils(utils将来存放配置文件和工具方法)
7.组件设计,在routes目录下新建三个文件:AAA.js BBB.js CCC.js
代码分别为:
AAA.js
import React, { Component } from 'react';
class AAA extends Component {
render() {
return (
<div>
<p>
AAA页
</p>
</div>
);
}
}
export default AAA;
BBB.js
import React, { Component } from 'react';
class BBB extends Component {
render() {
return (
<div>
<p>
BBB页
</p>
</div>
);
}
}
export default BBB;
CCC.js
import React, { Component } from 'react';
class CCC extends Component {
render() {
return (
<div>
<p>
CCC页
</p>
</div>
);
}
}
export default CCC;
8.model设计,在model下新建四个文件:aaa.js bbb.js ccc.js 和app.js(app作为全局model使用,将来存放全局变量,如国际化参数,登录用户信息等
代码分别为:
aaa.js
export default {
namespace: 'aaa',
state: {
name:'这是aaa的model'
},
subscriptions: {
},
effects: {
},
reducers: {
},
};
bbb.js
export default {
namespace: 'bbb',
state: {
name:'这是bbb的model'
},
subscriptions: {
},
effects: {
},
reducers: {
},
};
ccc.js
export default {
namespace: 'ccc',
state: {
name:'这是ccc的model'
},
subscriptions: {
},
effects: {
},
reducers: {
},
};
app.js
export default {
namespace: 'app',
state: {
name:'这是app的model'
},
subscriptions: {
},
effects: {
},
reducers: {
},
};
9.src目录下创建router.js路由控制文件,其中menuGlobal后期会提出到配置文件中,此处暂先这样放便于查看,大家发现其中也定义了id,pid,name,icon等字段,这些并不是dva路由必须字段,没错这些事自定义的字段,将来会用到,菜单关系,菜单是否显示,和icon图标等
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic'
const menuGlobal=[
{
id:'aaa',
pid:'0',
name:'aaa页',
icon:'user',
path: '/aaa',
models: () => [import('./models/aaa')], //models可多个
component: () => import('./routes/AAA'),
},
{
id:'bbb',
pid:'0',
name:'bbb页',
icon:'user',
path: '/aaa/bbb',
models: () => [import('./models/bbb')], //models可多个
component: () => import('./routes/BBB'),
},
{
id:'ccc',
pid:'0',
name:'ccc页',
icon:'user',
path: '/ccc',
models: () => [import('./models/ccc')], //models可多个
component: () => import('./routes/CCC'),
},
];
function RouterConfig({ history, app }) {
return (
<Router history={history}>
<Switch>
{
menuGlobal.map(({path,...dynamics},index)=>(
<Route
key={index}
path={path}
exact
component={dynamic({
app,
...dynamics
})}
/>
))
}
</Switch>
</Router>
);
}
export default RouterConfig;
10.修改src目录下index.js入口文件:.
import dva from 'dva';
import './index.css';
import createHistory from 'history/createBrowserHistory'
// 1. Initialize
const app = dva({
history:createHistory()
});
// 2. Plugins
// app.use({});
// 3. Model
app.model(require('./models/app').default);
// 4. Router
app.router(require('./router').default);
// 5. Start
app.start('#root');
然后就可以运行了