首页 > 解决方案 > 什么是最佳实践,直接在渲染或状态中使用 const?

问题描述

我是新手,请帮助我了解最佳实践。

我应该直接在渲染或状态中使用 const 吗?

下面是示例代码。

import React, { Component } from 'react';

    class VehicleDetail extends Component{
        constructor(props){
           super(props);
           this.state = {vehicle: [] };
        }

    componentDidMount() {

            axios.get(`/getDetails/${this.props.match.params.id}`)
                .then(response => {
                    this.setState({ vehicle : response.data.vehicle });
                });
        }

    render() {

        const vehicle = this.state.vehicle;

        return(
            <div className="col-12 col-md-5 car-price-detail">
                <h3>{vehicle.title}</h3>
                <h5><span>Mileage:</span> {vehicle.mileage}</h5>
                <h5><span>Color:</span> {vehicle.exterior_color}</h5>
            </div>
        );
    }
}

import React, { Component } from 'react';

    class VehicleDetail extends Component{
        constructor(props){
           super(props);
           this.state = {vehicle: [] };
        }

    componentDidMount() {

            axios.get(`/getDetails/${this.props.match.params.id}`)
                .then(response => {
                    this.setState({ vehicle : response.data.vehicle });
                });
        }

    render() {

        return(
            <div className="col-12 col-md-5 car-price-detail">
                <h3>{this.state.vehicle.title}</h3>
                <h5><span>Mileage:</span> {this.state.vehicle.mileage}</h5>
                <h5><span>Color:</span> {this.state.vehicle.exterior_color}</h5>
            </div>
        );
    }
}

标签: javascriptreactjsecmascript-6

解决方案


ESLINT 建议您使用解构变量:

const { vehicle } = this.state;

推荐阅读