为什么我的道具没有传递给子组件?

时间:2019-05-09 17:24:13

标签: reactjs react-props

我试图在React中创建一个模式,当点击button中的App.js时显示一些信息。

当我将模式代码放入App.js时,它成功填充了数据(尽管每个li一次)。

我将模态移到了它自己的组件上,但是我得到了Cannot read property 'name' of undefined

这是我的App.js代码:

const APIURL = 'https://api.openbrewerydb.org/breweries?';
const citySearch = 'by_city=boston';

class App extends Component {
  constructor(props) {
    super(props)

    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);

    this.state = {
      error: null,
      isLoaded: false,
      breweries: [],
      show: false
    };
  }

  handleClose() {
    this.setState({ show: false });
  }

  handleShow() {
    this.setState({ show: true });
  }

  componentDidMount() {
    fetch(APIURL + citySearch)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            breweries: result
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, breweries } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
    return (
      <div>
        <ul>
        {breweries.map(brewery => (
          <div className="brewery-card">
          <li key={brewery.id}>
          <p id="brewery-name">{brewery.name}</p>
          <p id="brewery-type">{brewery.brewery_type}</p> 
          <p id="brewery-address">{brewery.street} {brewery.city}, {brewery.state} {breweries.postal_code} </p>
          <button onClick={this.handleShow}>Details</button>
          <a href={brewery.website_url} target="_blank" rel="noopener noreferrer">Visit Site</a>
          </li>
          </div>
        ))}
      </ul>
      <DetailsModal props={this.props.brewery} show={this.state.modalShow} />
      </div>
     );
    }
  }
}

export default App;

这是我的组件代码,没有收到道具:

import React, { Component } from 'react';
import { Modal, Button } from 'react-bootstrap'

class DetailsModal extends Component {
    constructor(props) {
        super(props);

        this.state = {
            show: false
        };
    }
    render() {

        const brewery = this.props.brewery;

        return (
            <Modal {...this.props}>
            <Modal.Header closeButton>
              <Modal.Title>{brewery.name}</Modal.Title>
            </Modal.Header>
            <Modal.Body>{brewery.street} {brewery.city}, {brewery.state} {brewery.postal_code}</Modal.Body>
            <Modal.Footer>
              <Button variant="secondary" onClick={this.handleClose}>
                Close
              </Button>
            </Modal.Footer>
          </Modal>
        )
    }
}

  export default DetailsModal;

我缺少什么阻止App.js中使用道具DetailsModal.js

1 个答案:

答案 0 :(得分:1)

您传递的道具名称错误(或访问错误)

<DetailsModal props={this.props.brewery} show={this.state.modalShow} />

应该是

//              \/ here
<DetailsModal brewery={this.props.brewery} show={this.state.modalShow} />

当您执行const brewery = this.props.brewery;时,您尝试从道具访问brewery,但没有在道具中提供brewery,只有propsshow

这里是一个示例,以阐明正在发生的事情。

您要将someProp传递给ComponentX

ComponentX this.props内部将是带有传递的道具的对象,在这种情况下,它将是

{
    someProp: "something"
}

所以this.props.someProp返回"something"

如果您尝试访问this.props.someOtherProp,它将返回undefined。 而且,如果您尝试访问this.props.someOtherProp.X,则会收到annot read property 'X' of undefined

错误

如果您在理解道具的工作方式时遇到问题,请查看文档中的examples

编辑:

出现错误的另一个原因是App this.props.brewery中不存在。

只有与brewerybreweries有关的事物处于您的状态。

这是另一个错误。并且您需要指定要在DetailsModal

中显示的内容

编辑2:

要在单击时显示啤酒厂,您需要保持所单击啤酒厂的值并将其传递给模态

  1. 添加到App状态currentBrewery

    this.state = {
        error: null,
        isLoaded: false,
        breweries: [],
        show: false,
        currentBrewery: {}
    };
    
  2. 添加到onClick中以将currentBrewery中的brewery设置为breweries

    <button onClick={() => this.handleShow(brewery)}>Details</button>
    

    handleShow(brewery) {
        this.setState({ show: true, currentBrewery: brewery });
    }
    
  3. DetailsModal currentBrewery您所在的州

    <DetailsModal brewery={this.state.currentBrewery} show={this.state.modalShow} />