简体   繁体   English

反应中的分页不起作用。 加载后额外添加到 URL 字符串

[英]Pagination in react not working. Adds in extra to the URL string once loaded

hi hope someone can help me.嗨希望有人可以帮助我。 I have added pagination into my react app.我在我的反应应用程序中添加了分页。 I have checked and the query strings are working as they should be on the back end.我已经检查并且查询字符串正在工作,因为它们应该在后端。 However when I try and click through the pagination buttons it adds extra to the URL so instead of localhost:3000/topic/page/1 it is localhost:3000/topic/page/topic/page/1.但是,当我尝试单击分页按钮时,它会为 URL 添加额外的内容,因此它不是 localhost:3000/topic/page/1,而是 localhost:3000/topic/page/topic/page/1。 Therefore I get a not found error when I click on the link.因此,当我单击链接时出现未找到错误。

Routes file路由文件

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Register from '../auth/Register';
import Login from '../auth/Login';
import Alert from '../layout/Alert';
import Dashboard from '../dashboard/Dashboard';
import CreateProfile from '../profile-forms/CreateProfile';
import EditProfile from '../profile-forms/EditProfile';
import Profiles from '../profiles/Profiles';
import Profile from '../profile/Profile';
import Posts from '../posts/Posts';
import Post from '../post/Post';
import Topics from '../topic/Topics';
import Flashcard from '../flashcard/Flashcard';
import Quiz from '../quiz/Quiz';
import Factsheet from '../factsheet/Factsheet';
import NotFound from '../layout/NotFound';
import PrivateRoute from '../routing/PrivateRoute';

const Routes = () => {
  return (
    <section className="container">
      <Alert />
      <Switch>
        <Route exact path="/register" component={Register} />
        <Route exact path="/login" component={Login} />
        <PrivateRoute exact path="/profiles" component={Profiles} />
        <PrivateRoute exact path="/profile/:id" component={Profile} />
        <PrivateRoute exact path="/dashboard" component={Dashboard} />
        <PrivateRoute exact path='/create-profile' component={CreateProfile} />
        <PrivateRoute exact path='/edit-profile' component={EditProfile} />
         <PrivateRoute exact path='/topic' component={Topics} />
        <PrivateRoute exact path='/topic/search/:keyword' component={Topics} />
        <PrivateRoute exact path='/topic/page/:pageNumber' component={Topics} />
        <PrivateRoute exact path='/topic/search/:keyword/page/:pageNumber' component={Topics} />
        <PrivateRoute exact path='/topic/flashcard/:id' component={Flashcard} />
        <PrivateRoute exact path='/topic/quiz/:id' component={Quiz} />
        <PrivateRoute exact path='/topic/factsheet/:id' component={Factsheet} />
        <PrivateRoute exact path="/posts" component={Posts} />
        <PrivateRoute exact path="/posts/:id" component={Post} />
        <Route component={NotFound} />
      </Switch>
    </section>
  );
};

export default Routes;

Paginate.js分页.js

import React from 'react'
import { Pagination } from 'react-bootstrap'
import { Link } from 'react-router-dom';
import { LinkContainer } from 'react-router-bootstrap'

const Paginate = ({ pages, page, keyword = '' }) => {
  return (
    pages > 1 && (
      <Pagination>
        {[...Array(pages).keys()].map((x) => (
          <LinkContainer
            tag={Link}
            key={x + 1}
            to={keyword
                  ? `topic/search/${keyword}/page/${x + 1}`
                  : `topic/page/${x + 1}`
            }
          >
            <Pagination.Item active={x + 1 === page}>{x + 1}</Pagination.Item>
          </LinkContainer>
        ))}
      </Pagination>
    )
  )
}

export default Paginate

SearchBox.js搜索框.js

import React, { useState } from 'react'
import { Form, Button } from 'react-bootstrap'


const SearchBox = ({ history }) => {
    const [keyword, setKeyword] = useState('')

    const submitHandler = (e) => {
        e.preventDefault() 
            if(keyword.trim()) {
                history.push(`/topic/search/${keyword}`)
            } else {
                history.push('/topic')
            }
        }
        
    return (
        <Form onSubmit={submitHandler} inline>
            <Form.Control 
                type="text" 
                name="q" 
                onChange={(e) => setKeyword(e.target.value)}
                placeholder="Search Topics....."
            ></Form.Control>
        </Form>

    )
}


export default SearchBox

topic.js主题.js

import React, { Fragment, useEffect } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import Paginate from '../layout/Paginate'
import TopicItem from './TopicItem';
import { getTopics } from '../../actions/topic';



const Topics = ({ getTopics, topic: { topics, loading, pages, page }, match }) => {
    const keyword = match.params.keyword
    const pageNumber = match.params.pageNumber || 1

    useEffect(() => {
        getTopics(keyword, pageNumber);
    }, [getTopics, keyword, pageNumber])

    return (
        <Fragment>
            {loading ? (
                <Spinner />
            ) : (
                <Fragment>
                    <h1 className="large text-primary1 my-2">Pick a Topic</h1>
                    <Link to="/topic" className="btn my-4">
                        Back To Topics
                    </Link>
                    <div className="card-grid-home">
                        {topics.length > 0 ? (
                            topics.map(topic => (
                                <TopicItem key={topic._id} topic={topic} />
                            ))
                        ) : (
                            <h4>No topics found......</h4>
                        
                        )}
                    </div>
                    <Paginate pages={pages} page={page} keyword={keyword ? keyword : ''}/>
                </Fragment>
            )}
        </Fragment>
    )

};

Topics.prototype = {
    getTopics: PropTypes.func.isRequired,
    topic: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    topic: state.topic
})

export default connect(mapStateToProps, { getTopics })(Topics)

Thanks in advance提前致谢

Realised that I was missing a / for the start of the routes.意识到我在路线开始时错过了 / 。 Silly mistake.愚蠢的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM