ReactJS技术问题:无法通过Route向子组件传递props
问题原因&解决方案
嘿,这个坑我刚学React的时候也踩过!你报错的核心原因是**this的作用域不对**:
你在PortfolioPage组件类的外部定义了const URL = this.props.interiorsUrl,这时候组件还没有被实例化,this根本不是组件的实例对象,自然找不到props属性,所以才会抛出TypeError: Cannot read property 'interiorsUrl' of undefined的错误。
父组件通过Route的render方法传递props的写法是完全正确的,问题全在子组件的代码上,给你几个可行的修正方案:
方案1:直接在方法里使用props(最简单)
把URL的引用直接放到componentDidMount里,用this.props.interiorsUrl就行:
componentDidMount() { axios.get(this.props.interiorsUrl) // ... 其余代码 }
方案2:在类内部定义可复用的URL
如果这个URL需要在多个方法里复用,可以把它存在组件实例上:
方式一:在构造函数里初始化
class PortfolioPage extends Component { constructor(props) { super(props); this.state = { result: [] }; this.URL = props.interiorsUrl; // 直接从构造函数的props参数获取 } componentDidMount() { axios.get(this.URL) // ... 其余代码 } }
方式二:使用类字段(ES7+语法,需确保项目支持)
可以直接在类内部定义字段,不用写在构造函数里:
class PortfolioPage extends Component { URL = this.props.interiorsUrl; // 类字段中可直接访问this.props constructor(props) { super(props); this.state = { result: [] }; } componentDidMount() { axios.get(this.URL) // ... 其余代码 } }
方案3:用getter动态获取URL
如果URL可能随props变化而更新,用getter可以保证每次拿到的都是最新值:
class PortfolioPage extends Component { get URL() { return this.props.interiorsUrl; } componentDidMount() { axios.get(this.URL) // ... 其余代码 } }
选其中一种方案修改子组件代码,就能解决这个报错啦~
内容的提问来源于stack exchange,提问作者claudiopb
相关产品推荐
相关产品推荐

