状态组件调用功能组件更改类型的建议

时间:2019-03-15 02:52:42

标签: javascript reactjs

我是新来的反应者。我想在有状态组件调用的功能组件中渲染数组。

我该怎么做,导致类组件中的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

1 个答案:

答案 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 (
        ...
  );
};