我设法使用以下代码获取数据并显示给 UI:
export default class BoxGarage extends Component {
render() {
let garage = this.props.garage;
garage.name = garage.name.replace('strtoreplace', 'My Garage');
let cars = garage.cars.length ?
garage.cars.map((val, key) => {
return (
<Car key={key} car={val} />
)
}) : (
<View style={styles.boxEmpty}>
<Text style={styles.textEmpty}>(No Cars)</Text>
</View>
);
return (
<View style={styles.boxGarage}>
<Text>{ garage.name }</Text>
{ cars }
</View>
)
}
}
然后我试图用一个函数来改变,但没有显示汽车。什么东西少了?
export default class BoxGarage extends Component {
render() {
let garage = this.props.garage;
garage.name = garage.name.replace('strtoreplace', 'My Garage');
cars = function(garage) {
if (garage.cars.length) {
garage.cars.map((val, key) => {
return (
<Car key={key} car={val} />
);
});
}
else {
return (
<View style={styles.boxEmpty}>
<Text style={styles.textEmpty}>(No Cars)</Text>
</View>
);
}
}
return (
<View style={styles.boxGarage}>
<Text>{ garage.name }</Text>
{ cars(this.props.garage) }
</View>
)
}
}
而且我认为我应该使用构造函数重构最佳实践,或者只是将函数移到渲染之外,但我不知道它是什么。请指教。
您的第二个代码不起作用的原因是,如果garage.cars.length > 0,您不会从函数中返回任何内容。
if (garage.cars.length) {
// Added a return statement on the next line
return garage.cars.map((val, key) => {
return (
<Car key={key} car={val} />
);
});
}
也就是说,我认为您的代码的第一个版本要清晰得多。如果一段代码变得足够复杂,以至于我很想制作一个内联函数来进行计算,我要么将其拉出到另一个类方法,或另一个组件。不过,在您的情况下,只执行三元或 if/else 会好得多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句