react + antiDesign开发中遇到的问题记录
一:页面中子路由失效:
antiDesign的官方实例中,会把路由重复的地方给去重,而且路由匹配模式不是严格模式。所以我们需要在util.js修改两个地方
1:把路由匹配模式改为严格:
export function getRoutes(path, routerData) {
let routes = Object.keys(routerData).filter(routePath =>
routePath.indexOf(path) === 0 && routePath !== path);
// Replace path to '' eg. path='user' /user/name => name
routes = routes.map(item => item.replace(path, ''));
// Get the route to be rendered to remove the deep rendering
const renderArr = getRenderArr(routes);
// Conversion and stitching parameters
const renderRoutes = renderArr.map((item) => {
// const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
return {
...routerData[`${path}${item}`],
key: `${path}${item}`,
path: `${path}${item}`,
exact: true,
};
});
return renderRoutes;
}
2:修改路由去重
function getRenderArr(routes) {
const renderArr = [];
renderArr.push(routes[0]);
/** *去掉重复判断,满足/user,/user/detail类似URL的情况 */
// for (let i = 1; i < routes.length; i += 1) {
// let isAdd = false;
// // 是否包含
// isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
// // 去重
// renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
// if (isAdd) {
// renderArr.push(routes[i]);
// }
// }
for (let i = 1; i < routes.length; i += 1) {
renderArr.push(routes[i]);
}
return renderArr;
}
二:表单类问题
1:双向数据绑定没有效果
错误代码:(这里的input被div包着)
endTime: {
name: '结束日期',
rule: {
rules: [],
initialValue: fileds && fileds.endTime,
},
component: () => {
return (
<div style={{ display: 'flex' }}>
<Input placeholder="请输入" style={{ borderRadius: 0 }} />
</div>
);
},
},
正确代码: component返回的表单元素不要有其他元素包着
endTime: {
name: '结束日期',
rule: {
rules: [],
initialValue: fileds && fileds.endTime,
},
component: () => {
return (
<Input placeholder="请输入" style={{ borderRadius: 0 }} />
);
},
},
三:父子组件传值的问题
1:子组件在接收父组件渲染的时候,只初始化渲染一次,父组件值改变后,子组件不会重新渲染。
错误代码: 在子组件的willmount或者didmount接收了父组件的值。
componentDidMount() {
const { ProductItemData } = this.props;
this.setState({
ProductItemData,
});
}
正确代码: 在componentWillReceiveProps中接收父元素数据。
componentWillReceiveProps(nextProps) {
const { ProductItemData } = this.props;
this.setState({
ProductItemData,
});
}
四:编写组件
1:组件使用默认属性defaultProps
const MyFunctionalComponent=(props)=>{
return (
<div>
<p>{props.name}</p>
</div>
);
}
MyFunctionalComponent.defaultProps={
name:'default name'
};
五:请求
1:如何在axios拦截时修改headers中的值(例如多语言)
axios.interceptors.request.use(
(config) => {
const config2 = config;
config2.timeout = 30000; //eslint-disable-line
config2.headers['Accept-language'] = 'USSSSS';
return config2;
},
(error) => {
// Do something with request error
return Promise.reject(error);
}
);
如果这里直接操作config会报 no-param-reassign 的错误。