van*_*eek 6 reactjs react-router
我试图通过将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;
Run Code Online (Sandbox Code Playgroud)
小智 10
React-Router的Route组件match通过props 将对象传递给它默认包装的组件.尝试constructor使用以下方法替换您的方法:
constructor(props) {
super(props);
this.state = {
instructors: [],
instructorID : props.match.params.instructorID
};
}Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
11027 次 |
| 最近记录: |