商品分类管理

表格显示

1
2
3
4
5
6
<Table
bordered={false}
rowKey='_id'
dataSource={dataSource}
columns={columns}
></Table>

通过dataSource获取数据源,columns指定每一列。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const dataSource = [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号',
},
];

const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
// 返回需要显示的样式
render: () => (
<span>
<LinkButton>修改</LinkButton>
<LinkButton>引入</LinkButton>
</span>
)
},
];

render通过此属性可以渲染其他组件

二级分类

state中定义数据以表示当前获取分类是一级分类还是二级分类

1
2
3
4
5
6
7
8
state = {
loading: false, // 是否正在获取数据中
categorys: [], // 一级分类列表
subCategorys: [], // 二级分类列表
parentId: '0', // 当前需要显示的分类列表的父分类ID
parentName: '', // 当前需要显示的分类列表的父分类名称
showStatus: 0 // 标识添加/更新的确认框是否显示, 0: 都不显示, 1: 显示添加, 2: 显示更新
}

此时获取分类的逻辑就要根据state中的数据进行动态调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 发送异步请求获取数据
getCategories = async () => {
this.setState({ loading: true })
const { parentId } = this.state
const result = await reqCategorys(parentId)
this.setState({ loading: false })
if (result.status !== 0) return message.error('获取列表失败')
const categorys = result.data
if (parentId === '0') {
this.setState({ categorys })
} else {
this.setState({ subCategorys: categorys })
}
}

默认获取一级分类,通过修改state里数据的状态即可调整为获取二级分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 获取指定分类下的二级分类
showSubCategorys = async (category) => {
// 先更新状态在调用
this.setState(
{
parentId: category._id,
parentName: category.name
},
// setState为异步,因此需要使用回调函数
() => {
this.getCategories()
}
)
}

setState是异步的。因此需要传入第二个参数回调函数。

子组件向父组件传递

1
2
3
4
5
6
<UpdateForm
categoryName={category.name}
setForm={(form) => {
this.form = form
}}
/>

父组件向子组件传递一个函数,其形参赋值为父组件this.form

1
2
3
4
5
componentDidMount() {
// console.log(this.props)
// 将form对象通过setForm传递给父组件
this.props.setForm(this.formRef.current)
}

子组件调用此函数并传入form对象