在 React.js 中,数组值没有通过 props 正确传递?

In React.js array value is not passing properly via props?

我有一个 React 应用程序,它有两个组件,一个是 Customer,另一个是 Tags。客户将其状态的标签值发送给标签。如下:

Customer.jsx

import React from "react";
import Tags from "./Tags.jsx";

export default class Customer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {customer:''};
  }
  componentDidMount(){
    const url = `http://localhost:3000/api/customers/${this.props.params.id}`
    fetch(url)
      .then(res=>res.json())
      .then(data=>{
        console.log(data);
        this.setState({
          customer: data
        });
      })
      .catch(error=>{
        console.log(error)
      });
  }
  render() {
    return (
      <div>
          Company Name :{this.state.customer.companyName}
          Customer Name :{this.state.customer.name}
          Tags: <Tags tags={this.state.customer.tags} />
      </div>
    );
  }
}

Tags.jsx

import React from "react";

export default class Tags extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    let tags = this.props.tags.map(tag=>{
      return (<span>tag</span>);
    });
    return (
      <div>
        {tags}
      </div>
     );
  }
}

当我 运行 我得到代码时,"TypeError: Cannot read property 'map' of undefined(…)"。如果我从下面替换 Tags.jsx

let tags = this.props.tags.map(tag=>{
          return (<span>tag</span>);
        });

console.log(this.props.tags);

输出是一个数组。 怎么了?我真的不明白。我能做什么?

未定义,因为您正在进行 API 调用并且数据尚未返回。

在您的 Customer 组件中,您可以检查 this.state.customer.tags 是否存在,如果存在 - 然后呈现标签。

类似的东西:

{ this.state.customer.tags ? <Tags tags={this.state.customer.tags} /> : null }

Customer 的构造函数中,您将 customer 的状态定义为字符串,而不是对象。您应该更改它以反映实际的客户属性,即:

 this.state = {customer: {name: '', tags: []}};