React组件未安装

时间:2018-01-12 23:59:46

标签: reactjs react-router

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

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

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 (
    <div className="box">
      <h1>Student:</h1>
      <h1>{this.state.studentInfo.first_name}           
{this.state.studentInfo.last_name}</h1>
      <h3>Grade: {this.state.studentInfo.grade}</h3>
      <h3>Email: {this.state.studentInfo.email}</h3>
    </div>
  )
}
}

我在students.js文件的componentDidMount方法中尝试了一个console.log来查看它是否正常安装,我发现它不会触发。当我尝试使用React Dev Tools检查状态时,我发现没有状态。

我有一个名为classList.js的类似组件,它具有类似的设置,可以正常工作。

classList.js:

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}`}><h3>{student.first_name} 
{student.last_name}</h3></Link>
)
return (
  <div className="box">
    <h1>{this.props.match.params.class}</h1>
    <h2>ClassList:</h2>
    {students}
  </div>
)
}

}

我检查了我的路线和链接标签,看起来很好。

Routes.js:

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 个答案:

答案 0 :(得分:1)

我很确定它找不到学生路线,因为你错过了/

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

应该是

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