首先,打开项目时 先创建路由
路由内可以 传组件 components 里面是布局的组件
import React, { useState } from 'react'
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons'
import { Menu } from 'antd';
import './styles.less'
export default function BasicLayout (props) {
const { history } = props
// 控制展开
const [openKeys, setOpenKeys] = useState(['sub1']);
// menu 选中
const [selected, setSelected] = useState(['/detail']);
// 展开的事件监听
const onOpenChange = (keys) => {
const value = keys.filter(dt => dt !== openKeys[0])
setOpenKeys(value)
};
function getItem (label, key, icon, children, type) {
return {
key,
icon,
children,
label,
type,
};
}
const items = [
// sub1 是 key 选中用的 这里可以写入需要添加的页面
getItem('选项一', 'sub1', <MailOutlined />, [
// getItem('添加', '/user/up'),
// getItem('编辑', '/user/hui'),
// getItem('首页', '/user/list'),
]),
];
// 点击切换 menu 选中
const onSelect = (item) => {
const { selectedKeys, key } = item
setSelected(selectedKeys) // 修改选中的 menu
history.push(key)
}
return (
<div className="layout-basic">
<Menu
mode="inline"
openKeys={openKeys} // 默认展开哪个菜单
onOpenChange={onOpenChange} // 展开 menu 的监听
onSelect={onSelect} // 点击选中的监听
selectedKeys={selected} // selectedKeys 菜单选中
style={{width: 270}}
items={items} // menu 数据
/>
{/* 右侧的布局 */}
<div className="layout-basic-children">{props.children}</div>
</div>
)
}
还可以传入 wrapper 写上路由守卫的布局
import React, { useEffect } from 'react';
import { Redirect, getDvaApp } from 'umi';
import { connect } from 'dva';
export default connect((state) => {
return {};
})(Authorized);
function Authorized(props) {
if (localStorage.getItem('token')) {
return props.children;
} else {
return <Redirect to="/user/login" />;
}
}
在这个地方 配置
接口前缀
练习:
model:
import { pathToRegexp } from 'path-to-regexp';
import { history } from 'umi';
import is from 'is_js';
import _ from 'lodash';
import api from '@/services';
import { message } from "antd"
// 全局
export default {
namespace: 'dva',
state: {
count: 0,
data: [],
},
reducers: {
setData(state, { payload }) {
const {count,list}=payload
return {
...state,
data: list,
count:count,
}
}
},
effects: {
// 商品列表接口
* fetchTable({ payload }, { call, put, select }) {
// const res = yield call(() => api.fetchSampleList(payload))
const res=yield call(api.fetchSampleList,payload)
if (!res.code) {
yield put({
type: 'setData',
payload: res.result
})
}
},
}
};
在外层index.jsx文件里写上
import React, { useEffect } from 'react';
import { connect } from 'dva';
export default connect((state) => {
return {
data: state.dva.data,
count: state.dva.count,
};
})(Dva);
function Dva(props) {
const { dispatch, data, count } = props;
useEffect(() => {
dispatch({
type: 'dva/fetchTable',
payload: {
token: '6rL2FBOjZGfOz5eB8DUbvUIPKOE90tmn',
id: 1,
page: 1,
limit: 1,
},
});
}, []);
return <div>dva</div>;
}
版权声明:本文为SongdanDab原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。