我有新的反应,请帮助我了解最佳做法。
我应该直接在渲染或状态中使用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>
);
}
}
ESLINT建议您使用destructuring您的变量:
const { vehicle } = this.state;
你可以使用destruct作为ESLINT建议。通过解构,您的每一条线看起来都会更少。
另外,考虑一下情况,
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>
);
你在这里直接使用状态变量。也可能有更多的线路。如果您将来某个时候需要更改状态变量vehicle
,则无论您在何处使用它都需要更改每一行。这是一个糟糕的代码练习。此外,这也会影响您的代码维护。这就是我们使用解构的原因
const { vehicle } = this.state;
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>
);
使用此代码,如果出现这种情况,您将只有一行更改。这是一个很好的做法。这些是我所知道的一些原因。如果有其他人知道更多,请填写。非常感谢。
我相信这没关系。使用您认为适合您的方法。在这种情况下,我个人使用解构变量。
没有最佳实践,这是一种风格问题。请注意,由于props和state属性可能具有相同的名称,因此过度的解构可能会导致命名冲突并导致不一致:
render() {
const { vehicle } = this.state;
const { vehicle: vehicleProp } = this.props;
...
保持对象的参考不那么模糊,这导致更详细但更容易理解的代码,因为使用state
和props
对象讲述了组件如何工作:
const { state, props } = this;
...
{state.vehicle || props.vehicle}
...
虽然this.state
和this.props
在JSX表达式中过多(也与功能组件不一致)。