在React.js中数组值是不是通过道具正确传递?

时间:2016-11-30 09:20:16

标签: reactjs ecmascript-6 react-jsx

我有一个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>
     );
  }
}

当我运行我得到的代码时,&#34; TypeError:无法读取属性&#39; map&#39;未定义的(...)&#34;。如果我在下面替换Tags.jsx

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

console.log(this.props.tags);

输出是一个数组。 怎么了?我真的不明白。我该怎么办?

2 个答案:

答案 0 :(得分:1)

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

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

那样的东西:

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

答案 1 :(得分:1)

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

 this.state = {customer: {name: '', tags: []}};
相关问题