我是新来的反应者。我想在有状态组件调用的功能组件中渲染数组。
我该怎么做,导致类组件中的Array更改为被调用组件中的对象?
class Vehicles extends Component {
state = { vehicles: [] };
componentDidMount() {
fetch('http://localhost:8080/api/vehicles')
.then((Response) => Response.json())
.then((res) => {
this.setState({ vehicles: res });
})
.catch((error) => {
console.log(error);
});
}
render() {
console.log('Stateful Component:', this.state.vehicles);
console.log(this.state.vehicles instanceof Array);
if (this.state.vehicles.length > 0) {
return <VehicleList props={this.state.vehicles} />;
} else return null;
}
}
const VehicleList = (props) => {
console.log('Functional Component:', props);
console.log('Functional Component:', typeof props);
console.log(props instanceof Array);
return (
...
);
};
export default Vehicles;
控制台显示:
Stateful Component: (37) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
true
Functional Component: {props: Array(37)}
Functional Component: object
false
答案 0 :(得分:1)
是,因为组件的props
始终是对象。看到这行
<VehicleList props={this.state.vehicles} />;
您正在将props
设置为this.state.vehicles
,但您正在将props
设置为原始props
的属性。因此,您可以使用props.props
访问它。但是,由于名称相似,请使用
<VehicleList vehicles={this.state.vehicles} />;
然后在您的功能组件中
const VehicleList = (props) => {
const {vehicles} = props
console.log('Functional Component:', vehicles);
console.log('Functional Component:', vehicles);
console.log(vehicles instanceof Array);
return (
...
);
};