我应该如何在我的componentDidMount方法中访问数据?我已经将“ trainingID”发送到了组件中
<AthleteRegisterForm trainingID={this.props.match.params.trainingID}/>
现在我在组件中这样称呼它:
class AthleteRegisterForm extends React.Component {
trainingID = this.props.trainingID;
state = {
training: {}
}
componentDidMount() {
const trainingID = trainingID;
axios.get(`http://127.0.0.1:8000/api/${trainingID}`)
.then(res => {
this.setState({
training: res.data
});
})
}
trainingID = this.props.trainingID
在方法下,我只调用:
const trainingID = trainingID;
我应该改变什么?
答案 0 :(得分:1)
初始化之前,您正在使用trainingID
。它是正确的。您已经在componentDidMount挂钩中使用const
进行了声明,并在类中使用了它。您想像这样使用它:
class AthleteRegisterForm extends React.Component {
constructor(props) {
// this is necessary to use it on componentDidMount
super(props)
//...
}
componentDidMount() {
const trainingID = this.props.trainingID;