我正在尝试通过将Match对象传递到我的react组件类中来使用我的url作为参数。但是,它不起作用!我在这里做错了什么?
当我将组件创建为JavaScript函数时,一切正常,但是当我尝试将组件创建为JavaScript类时,则无法正常工作。
也许我做错了什么?如何将Match对象传递到类组件中,然后使用该对象来设置组件的状态?
我的代码:
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的Route组件通过prop将match对象传递给默认情况下包装的组件。尝试用constructor以下方法替换您的方法:
Route
match
constructor
constructor(props) { super(props); this.state = { instructors: [], instructorID : props.match.params.instructorID }; }
希望这可以帮助。