javascript - 有状态组件调用功能组件的 Props 更改类型

标签 javascript reactjs

我是新来的 react 。我想在从有状态组件调用的功能组件中渲染一个数组。

我在做什么导致类组件中的数组更改为被调用组件中的对象?

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

最佳答案

是的,因为props组件的始终是一个对象。请参阅这一行

<VehicleList props={this.state.vehicles} />;

您正在设置propsthis.state.vehicles但你正在设置 props作为原件的属性(property) 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 (
        ...
  );
};

关于javascript - 有状态组件调用功能组件的 Props 更改类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174894/

相关文章:

javascript - 带样式的组件,在谷歌浏览器上中断

javascript - 在 React 组件的类之外编写函数

javascript - React - chop Markdown

javascript - Jquery 位置没有给出预期的结果

javascript - 在 Chrome 扩展中打开和关闭一个简单的弹出窗口

javascript - 使用在 Webpack 构建中公开全局变量的脚本

javascript - 在 promise 中设置状态时遇到困难

javascript - 为什么我可以使用 (myVar & 1) 来测试参与方以及我应该在 Javascript 中执行此操作吗?

javascript - Asp.Net MVC 中 JS 和 CSS 的压缩

javascript - 如何使用react加载外部脚本?