我试图通过将 Match 对象传递到我的 react 组件类来使用我的 url 作为参数.但是它不起作用!我在这里做错了什么?
当我将组件创建为 JavaScript 函数时,一切正常,但是当我尝试将组件创建为 JavaScript 类时,它不起作用.
也许我做错了什么?如何将 Match 对象传递给我的类组件,然后使用它来设置我的组件的状态?
我的代码:
import React, { Component } from 'react';从 'axios' 导入 axios;从 'prop-types' 导入 PropTypes;类 InstructorProfile 扩展组件 {构造函数(道具,{匹配}){超级(道具,{匹配});this.state = {导师:[],教员 ID : match.params.instructorID};}componentDidMount(){axios.get(`/instructors`).then(响应 => {this.setState({教师: response.data});}).catch(错误=> {console.log('获取和解析数据时出错', error);});}使成为(){返回 (<div className="instructor-grid"><div className="instructor-wrapper">你好);}}导出默认的 InstructorProfile;
解决方案React-Router 的 Route 组件默认通过 props 将 match 对象传递给它包装的组件.尝试用以下内容替换您的 constructor 方法:
constructor(props) {超级(道具);this.state = {导师:[],教员 ID : props.match.params.instructorID};}希望这会有所帮助.
I am trying to use my url as a parameter by passing the Match object into my react component class. However it is not working! What am I doing wrong here?
When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.
Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?
My code:
import React, { Component } from 'react'; import axios from 'axios'; import PropTypes from 'prop-types'; class InstructorProfile extends Component { constructor(props, {match}) { super(props, {match}); this.state = { instructors: [], instructorID : match.params.instructorID }; } componentDidMount(){ axios.get(`/instructors`) .then(response => { this.setState({ instructors: response.data }); }) .catch(error => { console.log('Error fetching and parsing data', error); }); } render(){ return ( <div className="instructor-grid"> <div className="instructor-wrapper"> hi </div> </div> ); } } export default InstructorProfile;解决方案
React-Router's Route component passes the match object to the component it wraps by default, via props. Try replacing your constructor method with the following:
constructor(props) { super(props); this.state = { instructors: [], instructorID : props.match.params.instructorID }; }
Hope this helps.
更多推荐
如何将 Match 对象包含到 ReactJs 组件类中?
发布评论