使用React Router显示详细信息

时间:2020-02-11 20:22:04

标签: reactjs

我有一个路由器来显示各个班级的详细信息。该代码可在我的本地计算机URL上用于详细信息视图http://localhost:3000/course/16623,但是当我将代码部署到Web服务器https://url/course/16623时却出现404错误。如何解决这个问题?谢谢。下面是我的代码:

Routing.js

 const Routing = () => (
    <Switch>
      <Route exact path='/course/:CLASS_NBR' component={Bookmark} />
      <Route  path="/" component={App} />
    </Switch>
     </>
    );
    export default Routing;

CourseDetail.js

...
 <Link  to={{ pathname: '/course/'+course.CLASS_NBR

            }}
            target="_blank"
                        key={course.ID}>
                        View this course
                    </Link>

Bookmark.js

 class Bookmark extends Component {
        state={
           CLASS_NBR: this.props.match.params.id, 
          course:[]
        };

        componentDidMount(){
           const {CLASS_NBR} = this.props.match.params.CLASS_NBR ;
            this.runSearch();
         }

         runSearch=async()=>{

           const response= await axios.get('url/api/get',
           {
              params: {
              CLASS_NBR: this.props.match.params.CLASS_NBR
              }
           })
           this.setState({course: response.data});
         }
      render(){
          if (!this.state.course){
              return <div>No record found</div>
          }

          const course =this.state.course;

          return (

             <div>
             <h4>
              {course["SUBJECT"]} {course["CATALOG_NBR"]} - {course["COURSE_DESCR"]}  
              </h4>

            </div>

      );
      }   
      };

    export default Bookmark;

2 个答案:

答案 0 :(得分:0)

React作为单页应用程序运行,因此您需要将所有请求路由到index.html。

将此添加到您的.htaccess文件中。

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

作为奖励,如果要构建404页面,可以使用React Router对其进行配置。

答案 1 :(得分:0)

我通过使用哈希路由找到了解决方案。请参阅此帖子https://muffinman.io/react-router-subfolder-on-server/