简体   繁体   中英

React Router V4 isnt working properly

I am making a web application in which iI want to display the details of the user when clicked on them in the same page using routers. here is my index.js page

window.React = React;

render(<div>
    <Menu/><MainMenu/><App/><Footer/>
</div>, document.getElementById('react-container'))

This is my App.js Page

class App extends Component {
  render () {
    return (

        <div>
            <BrowserRouter>
                   <Side>
                    <Route path="/" component={Side}>

                    <Route exact path="/" component={Home}/>
                    <Route path="/user-lists" component={Table}>
                    </Route>

                    </Route>

</Side>

            </BrowserRouter>
        </div>

    )
  }
}


export default App

this is my users page

export default class Table extends React.Component {
    constructor(props) {
        super(props);

        this.columns = [
            {
                name: "ID",
                key: "id"
            }, {
                name: "Name",
                key: "name"
            }, {
                name: "Username",
                key: "username"
            }, {
                name: "Email",
                key: "email"
            }, {
                name: "Website",
                key: "website"
            }
        ];

        this.maxItems = 5; 
    };

    state = {
        pgNo: 0,
        table: [],
        isFetching: true,
        url:"https://jsonplaceholder.typicode.com/users/"

    };
    componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/users")
            .then(response => response.json())
            .then(res => {
                this.setState({table: res, isFetching: false});

            });



        }



    render() {
        return this.state.isFetching
            ? (
                <div
                    className="loader"
                    style={{
                    marginLeft: "50%"
                }}>
                    <img src="/assets/index.svg"/>
                </div>
            )
            : (

                <MyTable pgNo ={this.state.pgNo}
                         maxItems = {this.maxItems}
                         columns={this.columns} 
                         data={this.state.table}
                         url={this.state.url}/>
            )
    }

}

Here is my Sidebar.js page

export const Side = () => 

<aside className="main-sidebar sidebar-dark-primary elevation-4">

    <a href="#" className="brand-link">
        <span className="brand-text font-weight-light">Dashboard</span>
    </a>

    <div className="sidebar">

        <div className="user-panel mt-3 pb-3 mb-3 d-flex">
            <div className="image"></div>
            <div className="info">
                <a href="#" className="d-block">Irtaza</a>
            </div>
        </div>

        <nav className="mt-2">
        <li><Link  to='/'>Home</Link></li>&nbsp;
        <li><Link  to='/posts'><Fausers /> Posts  </Link></li>&nbsp;
        <li><Link  to='/user-lists'><Fafile/> Users </Link></li>&nbsp;
        <li><Link  to='*'><Fatimes/> Whoops 404 </Link></li>

     </nav>

    </div>

</aside>

And finally this is my table.js page

export default class MyTable extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentPage: this.props.pgNo,
           details : [],
    id: null
        }
        this.MaxPages = 0;

    }

    PrevButton() {

        if (this.state.currentPage === 0) {
            return (null);
        } else {
            return (
                <button
                    type="button"
                    key={this.state.currentPage}
                    style={{
                    float: "left"
                }}
                    onClick=
                    { () => { this.setState({ currentPage: this.state.currentPage - 1 }) } }>
                    Previous Page
                </button>
            );
        }

    }

    NextButton() {
        if (this.state.currentPage === this.MaxPages - 1) {
            return (null);
        } else {
            return (

                <button
                    style={{
                    float: "right"
                }}
                    key={this.props.pgNo}
                    onClick={() => {
                    this.setState({
                        currentPage: this.state.currentPage + 1
                    })
                }}>
                    Next Page
                </button >
            );
        }
    }


    createTable = () => {

        let tableHeader = <thead>
            <tr>
                {this.props.columns.map(column => {
                        return <th key={column.name}>
                            {column.name}
                        </th>
                    })}
            </tr>

        </thead>;
        this.state.number = this.state.number + 1;
        let tableRows = [];
        for (let i = this.state.currentPage * this.props.maxItems; (i < (this.state.currentPage + 1) * this.props.maxItems) && (i <= this.props.data.length); i++) {

            this.state.id= i + 1;          

         let row = <Link to={{
            pathname: `/user-lists/details(/${i+1})`

          }}>

          <tr key={i}>
                {this
                    .props
                    .columns
                    .map(column => {
                        this.state.id= i + 1; 
                        return (
                            <td key={column.key}>

                                {this.props.data[i][column.key]}

                            </td>
                        )
                    })}

            </tr>
</Link>
            tableRows.push(row)
            }
        for (let i = 0; i <= Math.ceil(this.props.data.length / this.props.maxItems); i++) {
            this.MaxPages = i;

        }

        let tableBody = <tbody>{tableRows}</tbody>;
        return <table>{tableHeader}{tableBody}
        </table>;
    }

    render() {

        return (
            <div className="col-md-6">
                <div className="container-fluid">
                    <div
                        className="table table-bordered"
                        style={{
                        marginLeft: "70%",
                        marginRight: "5%"
                    }}>
                        {this.createTable()}
                        {this.PrevButton()}
                        {this.NextButton()}
                    </div>

                </div>
            </div>
        )
    }

}

Every time I click on a Link in sidebar.js it redirects me to the new link but does not render anything also it gives me an error "Failed to load resource: the server responded with a status of 404 (Not Found)" I dont know what i am doing wrong. Feel free to point out any mistakes you see.

Firstly , In order for Link to work correctly, it needs to Receive the Router Props but since its rendered as a Route, it doesn't receive any props.

Secondly all routes are defined as children to Side , but they are never rendered in the Side component

You would write your components like

App.js

class App extends Component {
  render () {
    return (
        <div>
            <BrowserRouter>
              <div>
                <Route component={Side}>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/user-lists" component={Table}>
                    <Route path="*" component={NotFound}/>
                </Switch>
              </div>
            </BrowserRouter>
        </div>
    )
  }
}


export default App

and Side.js

export const Side = (props) => (

    <aside className="main-sidebar sidebar-dark-primary elevation-4">

        <a href="#" className="brand-link">
            <span className="brand-text font-weight-light">Dashboard</span>
        </a>

        <div className="sidebar">

            <div className="user-panel mt-3 pb-3 mb-3 d-flex">
                <div className="image"></div>
                <div className="info">
                    <a href="#" className="d-block">Irtaza</a>
                </div>
            </div>

            <nav className="mt-2">
            <li><Link  to='/'>Home</Link></li>&nbsp;
            <li><Link  to='/posts'><Fausers /> Posts  </Link></li>&nbsp;
            <li><Link  to='/user-lists'><Fafile/> Users </Link></li>&nbsp;
            <li><Link  to='*'><Fatimes/> Whoops 404 </Link></li>

         </nav>

        </div>

    </aside>

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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