一、遇到的问题
多个页面共用一个js文件,在js中增加2个筛选条件框、1个列后,多个页面都增加了2个筛选条件框、1个列。
二、目标
其它页面要隐藏2个筛选条件框、1个列,只在指定的页面中显示。
三、解决方法
1.首先,在 项目/src/pages/ListPage/models/ListPage.js里,初始化一个变量pageFunction,用来保存进入了哪个页面的信息
import * as services from '@/services/api';
import { message } from 'antd';
export default {
namespace: "ListPage",
state: {
pageFunction '',
},
};
2.在 项目/src/pages/ListPage/index.jsx中,初始化方法里,给pageFunction赋值,用来判断进入了哪个页面:
//页面初始化会执行的方法
componentWillMount(){
const { dispatch } = this.props;
//这里可以获得路由路径,一般用于一个组件页面用于不同菜单时使用
const { match } = this.props;
if( match.path === '/mission/manage' ) {
dispatch({
type: 'ListPage/changePageFunction',
pageFunction: 'manage',
});
}
if( match.path === '/mission/mytask' ) {
dispatch({
type: 'ListPage/changePageFunction',
pageFunction: 'mytask',
});
}
}
3.在页面js文件中,获取该参数,判断是否隐藏展示列。这个列在数组中保存,因此需要根据参数决定是否移除数组中的某列。如下:
@Connect (({ ListPage }) => ({
ListPage,
}))
//某个方法,查询表格的列定义
getColumns = () => {
const { dispatch,codeselect, ListPage:{queryPara,pageFunction} } = this.props;
const columns = [
{
title: formatMessage({ id:'ListPage.name' }),
dataIndex: 'name',
align: 'center',
width: 200,
},{
title: formatMessage({ id:'ListPage.sex' }),
dataIndex: 'sex,
align: 'center',
width: 200,
render: (text) => {
return this.parseSex(text)
}
},{
title: formatMessage({ id:'ListPage.com' }),
dataIndex: 'com',
align: 'center',
width: 200,
}
];
//例如要把com列去掉
if(pageFunction === 'mytask') {
//去掉dataIndex为com的列(数组元素)
const columns1 = columns.filter(item=>item.dataIndex !== 'com')
return columns1;
}
return columns;
};
之后,这个方法在AdvancedTable标签处被调用,根据dataIndex的值,与json数组中的key名称相同,就能显示出数据了。如下:
<AdvancedTable
namespace="ListPage"
queryPara={queryPara}
data={data}
columns={this.getColumns()}
rowSelection={rowSelection}
loading={loading}
/>
其中,data对应json数组,例如[{"id":"1","name":"xxx","sex":"0","com":"A"}];getColumns()是上方的方法。
4.隐藏条件筛选框的方法类似,但是写法不同;条件筛选框是FormITem标签,根据不同情况隐藏的写法如下:
import {Form,Input,DatePicker,Select,TreeSelect,Button,Icon} from 'antd';
const FormItem = Form.Item;
@Connect(({ ListPage }) => ({
ListPage
}))
render() {
const {
ListPage:{ queryPara,pageFunction }
} = this.props;
//从props中拿到pageFunction,然后换了个常量
const showOption = pageFunction;
return (
<Form {...formItemLayout} onSubmit={} layout="inline">
{ showOption !== "mytask" ? (
<FormItem label={<FormattedMessage id="ListPage.com" />}>
...
</FormItem>
):null
}
{ showOption !== "mytask" ? (
<FormItem label={<FormattedMessage id="ListPage.name" />}>
...
</FormItem>
):null
}
</Form>
);
}
意思是,如果打开的不是mytask页面,则显示FormItem标签;否则不显示FormItem标签(null)。需要注意,一个?:表达式的大括号中,只能写一个要操作的标签(<FormItem>),如果要操作多个标签,则需要写多个?:表达式,如上方。
四、总结
React中,如果想根据页面不同,隐藏某些标签或进行某些操作,可以在页面的初始化方法里增加参数,将当前url存为变量;
其他页面中判断此变量,进行不同操作;
如果要进行数组删除某个元素的操作,可以使用Filter方法;
如果要进行隐藏标签的操作,可以使用?:表达式。
五、参考文章
https://blog.youkuaiyun.com/supperi/article/details/106927816