基本上,我在render函数内部的prop的组件内多次调用同一函数。
如何避免针对该特定道具所需的组件多次调用同一函数
下面是我的代码
getProperties = (name, param) => {
switch(name){
case 'duration':
return param.obj1;
case 'time':
return param.obj2;
case 'date':
return param.obj3;
case 'place':
return param.obj4;
}
}
render() {
return (
<SampleComponent
duration={this.getProperties('duration', param1)}
time={this.getProperties('time', param2)}
date={this.getProperties('date', param3)}
place={this.getProperties('place', param4)}
)
}
因此,不必使用多种方法来获取所需的详细信息。如何使用单一方法来操作并返回具有转换后数据的对象?
答案 0 :(得分:1)
这是清理代码的一种方法:
const DURATION = "duration";
const TIME = "time";
const DATE = "date";
const PLACE = "place";
const allParamters = [DURATION, TIME, DATE, PLACE]
paramMap
和keyMap
paramMap
是用于给定参数的对象。keyMap
是一张地图,上面会说明要为给定的参数使用哪个key
。const paramMap = {
[DURATION]: param1,
[TIME]: param2,
[DATE]: param3,
[PLACE]: param4
};
const keyMap = {
[DURATION]: "obj1",
[TIME]: "obj2",
[DATE]: "obj3",
[PLACE]: "obj4"
}
// for getProperties(DURATION), it will resolve to `param1.obj1!`
const getProperties = (key) => paramMap[key][keyMap[key]];
// this will prepare the `props` map as:
// { "duration": param1.obj1, ... }
const propsToPass = allParamters.reduce((props, aParam) => {
props[aParam] = this.getProperties(aParam)
return props;
}, {});
<SampleComponent {...propsToPass} />
您需要做的就是正确定义paramMap
,其中param1
,param2
和其他对象在范围内。
这是完整的代码段:
const DURATION = "duration";
const TIME = "time";
const DATE = "date";
const PLACE = "place";
const allParamters = [DURATION, TIME, DATE, PLACE]
const paramMap = {
[DURATION]: param1,
[TIME]: param2,
[DATE]: param3,
[PLACE]: param4
};
const keyMap = {
[DURATION]: "obj1",
[TIME]: "obj2",
[DATE]: "obj3",
[PLACE]: "obj4"
}
const getProperties = (key) => paramMap[key][keyMap[key]];
const propsToPass = allParamters.reduce((props, aParam) => {
props[aParam] = this.getProperties(aParam)
return props;
}, {});
<SampleComponent {...propsToPass} />
答案 1 :(得分:0)
obj1,obj2,obj3等来自哪里?他们是道具吗?
如果更容易,您还可以将对象作为组件的道具传播
即
const someObj = {
duration: obj1,
time: obj2,
date: obj3,
place: obj4
}
<SampleComponent {...someObj} />
这会将道具的持续时间,时间,日期,地点等添加到您的组件中。不知道我是否有足够的背景信息,但这也许可以帮忙
答案 2 :(得分:0)
我们可以做这样的事情-:
还为pops添加了null失败安全检查。
getPropsForSampleComponent = {
duration: obj1 || null,
time: obj2 || null,
date: obj3 || null,
place: obj4 || null
}
render() {
return (
<SampleComponent
{...this.getPropsForSampleComponent}
)
}