gpt4 book ai didi

javascript - ReactJS - 我无法通过 Route 为子组件传递 Prop

转载 作者:行者123 更新时间:2023-11-30 14:09:20 25 4
gpt4 key购买 nike

我有一个为子组件传递 Prop 的组件:

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

这是接收 Prop 的子组件:

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: Cannot read property 'interiorsUrl' of undefined

指向这行代码:

 const URL = this.props.interiorsUrl;

我做错了什么?谢谢。

最佳答案

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

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

例如:

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

关于javascript - ReactJS - 我无法通过 Route 为子组件传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com