关于reactjs:React组件无法挂载

React Component Does Not Mount

我需要一些帮助。我正在使用React-Router开发一个create-react-app。我看到的问题是,当我运行我的应用程序时,当我单击学生的姓名时,我应该能够看到他们的个人信息。相反,没有任何渲染。

以下是未呈现的组件(students.js)的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { Component } from 'react';
import axios from 'axios';

export default class Student extends Component {
constructor() {
  super();
  this.state = {
    studentInfo: {}
  }

}

componentDidMount(){
  console.log('fired')
  axios.get(`http://localhost:3005/students/${this.props.match.params.id}`)
  .then(res => {
    this.setState({studentInfo: res.data})
  })
  .catch(err => console.log(err))
}

render() {
  return (
   
      Student:
      {this.state.studentInfo.first_name}          
{this.state.studentInfo.last_name}
      Grade: {this.state.studentInfo.grade}
      Email: {this.state.studentInfo.email}
   
  )
}
}

我已经在我的students.js文件的componentDidMount方法中尝试了console.log,以查看它是否正确安装,并且发现它不会启动。当我尝试使用React Dev Tools检查状态时,发现没有状态。

我有一个名为classList.js的相似组件,该组件具有可以正常运行的相似设置。

classList.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { Component } from 'react';
import axios from 'axios';
import {Link} from 'react-router-dom';

export default class ClassList extends Component {
  constructor() {
  super();
  this.state = {
    students: []
}

}
componentDidMount(){
  axios.get(`http://localhost:3005/students?
  class=${this.props.match.params.class}`)
  .then(res => {
  this.setState({students: res.data});
  })
  .catch(err => console.log(err))}


render() {
const students = this.state.students.map((student,i) =>
  <Link key={i} to={`/student/${student.id}`}>{student.first_name}
{student.last_name}</Link>
)
return (
 
    {this.props.match.params.class}
    ClassList:
    {students}
 
)
}

}

我已经检查了我的路线和链接标记,它们看起来还不错。

Routes.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React from 'react';
import {Switch, Route} from 'react-router-dom';
import Home from './components/Home/Home';
import About from './components/About/About';
import ClassList from './components/ClassList/ClassList';
import Student from './components/Student/Student'

export default (
  <Switch>
    <Route exact path='/' component={Home} />
    <Route path='/about' component={About} />
    <Route path='/classlist/:class' component={ClassList} />
    <Route path='student/:id' component={Student} />
  </Switch>
)

有什么想法吗?谢谢!


我很确定它找不到学生路线,因为您缺少/

1
<Route path='student/:id' component={Student} />

应为

1
<Route path='/student/:id' component={Student} />