ReactJS-我无法为子组件传递proptrought Route

时间:2019-02-19 14:28:26

标签: javascript reactjs react-router-dom

我有这个组件,它为子组件传递了一个道具:

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'    
import PortfolioPage from './PortfolioPage'  

class PortfolioMenu extends Component {
  constructor(props) {
    super(props)
    // here is the prop to be passed for a child component
    this.state = {       
      interiorsUrl: "http://localhost:3001/interiors"
    }
  }

  render() {    
    return (
      <div>
        <Router>
          <div class="wrapper2">
            <div class="wrapper-portfolio">
              // here is the line to pass the prop
              <Route exact path='/portfolio/interiores' render={() => <PortfolioPage interiorsUrl={this.state.interiorsUrl}/>} />
            <nav>
              <ul>   
                <li><NavLink activeClassName="active" exact to="/portfolio/interiores">• interiores</NavLink></li>                  
              </ul>
            </nav>
          </div>
        </Router>
      </div>
    )
  }
}


export default PortfolioMenu

以下是接收道具的子组件:

import React, { Component } from 'react'
import axios from 'axios'
import Modal from 'react-responsive-modal';
import Lightbox from 'react-lightbox-component';


const URL = this.props.interiorsUrl;


class PortfolioPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result: []
    }

  }

  componentDidMount() {
    axios.get(URL)

//...rest of the code omitted

在上面的组件中,控制台上显示错误消息:

  

TypeError:无法读取未定义的属性'interiorsUrl'

指向此代码行:

 const URL = this.props.interiorsUrl;

我错了什么?谢谢。

2 个答案:

答案 0 :(得分:2)

您需要从组件内部调用this.props.interiorsUrl。

所以在下课后的任何地方{}

例如:

componentDidMount() {
    axios.get(this.props.interiorsUrl)
}

答案 1 :(得分:0)

class PortfolioPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result: []
    }

  }

  componentDidMount() {
    const { interiorsUrl } = this.props;
    axios.get(interiorsUrl)
      .then(response => this.setState({ result: response.data }))
      .catch(e => console.error(e));

  }
  //...rest of the code omitted