繁体   English   中英

道具未通过或渲染

[英]Props not being passed or rendered

大家好,我开始学习反应,我正在尝试将道具从一个组件传递到另一个组件,但没有呈现任何内容(或 console.logged )。

我非常感谢您的帮助

用户组件

export class Users extends React.Component {
  render() {
    const { name } = this.props.user;

    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
}

import { Users } from './users.jsx';

export class WhoWatch extends React.Component {
  state = {
    users: [
      { id: 1, name: 'Choo', series: ['Batman', 'Water'] },
      { id: 2, name: 'Sho', series: ['Boo', 'Too'] },
      { id: 3, name: "Cel'", series: ['Shoo', 'Rima'] },
    ],
  };

  // componentDidMount() {}

  render() {
    const { users } = this.state;
    return (
      <div>
        {users.map((user, index) => {
          <div>
            <Users user={user} key={index} />;
          </div>;
        })}
      </div>
    );
  }
}

name没有名为name的属性:

const { name } = this.props.name;

解构props

const { name } = this.props;

或者直接使用属性而不解构:

const name = this.props.name;

编辑:看起来您以多种方式混淆了“用户”和“名称”。 查看您传递给组件的内容:

<Users user={user.name} />

你想传递用户还是传递名称? 该组件当前需要一个名为name的道具,因此请传递:

<Users name={user.name} />

或者,您可以传递整个用户:

<Users user={user} />

然后在组件中解构user道具:

const { name } = this.props.user;

总体而言,这只是确保您传递的内容和您所期望的内容是同一件事的问题。 您可能会开始研究 TypeScript 以帮助在设计时执行此操作。

WhoWatch.js

import React, { Component } from 'react';
import Users from './Users';

class WhoWatch extends Component {
  state = {
    users: [
      { id: 1, name: 'Choo', series: ['Batman', 'Water'] },
      { id: 2, name: 'Sho', series: ['Boo', 'Too'] },
      { id: 3, name: "Cel'", series: ['Shoo', 'Rima'] },
    ],
  };

  render() {

    return (
      <div>
        {this.state.users.map((item) => {
            return <Users user={item} />;
        })}
      </div>
    );
  }
}

export default WhoWatch;

用户.js

import React, { Component } from 'react';

class Users extends Component {

  constructor(props){
    super(props);
    console.log(props);
  }
  
  render() {
    const { name } = this.props.user;

    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
}

export default Users;

Output:

在此处输入图像描述

WhoWatch组件中,您将用户名作为User组件上的user道具的值而不是用户 object 它自己传递。

 <Users user={user.name} />;

Users组件中,您试图通过解构user属性来获取name ,该属性不是 object 而是字符串。

您应该只传递整个 User object 而不仅仅是 name 属性。 因为这是该组件的目的,您应该像这样传递用户 object

 <Users user={user} />;

这将自动解决您的问题,因为您在 map 中,每个项目都必须具有这样的key属性

return (
  <div>
    {users.map((user, index) => {
      <div>
        <Users user={user} key={index}/>;
      </div>;
    })}
  </div>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM