【问题标题】:React Native: Access this.props Inside FunctionReact Native:访问 this.props 内部函数
【发布时间】:2018-12-16 22:41:57
【问题描述】:

我设法使用此代码获取数据并显示给 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>
        )
    }       
}

而且我认为我应该使用构造函数重构最佳实践,或者只是将函数移到渲染之外,但我不知道它是什么。请指教。

【问题讨论】:

  • 您的 if 案例没有返回语句,因此它隐式返回 undefined。

标签: javascript react-native


【解决方案1】:

第二个代码不起作用的原因是,如果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 会好得多。

【讨论】:

    猜你喜欢
    • 2017-05-06
    • 2016-07-27
    • 1970-01-01
    • 2021-12-07
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    相关资源
    最近更新 更多