React-Router v4问题 - URL更新但组件未重新呈现

时间:2018-01-13 20:55:51

标签: javascript reactjs react-router react-router-v4 react-router-dom

相当多的头衔。我有一个无序列表,但链接只更改URL,而不是页面上显示的实际组件。关于为什么会发生这种情况的任何想法?我想我已经包含了所有相关代码,但如果我遗漏了某些内容,请告诉我。谢谢!

App.js

sizeof(wchar_t)

Header.js

import React, { Component } from 'react';
import Header from './Header';
import Main from './Main';

    class App extends Component {
        render() {
            return (
            <div>
                <Header />
                <Main />
            </div>
    )
  }
}
export default App                    

Main.js

import React, {Component} from 'react';
import {Link} from 'react-router-dom';

class Header extends Component {
render() {
    return(
        <div>
            <hr />
            <div className="table">
                <ul id="horizontal-list">
                    <li><Link to='/'>Component1</Link></li>
                    <li><Link to='/ts'>Component2</Link></li>
                    <li><Link to='/cs'>Component3</Link></li>
                    <li><Link to='/cw'>Component4</Link></li>
                </ul>
             </div>
             <hr />
        </div>

    );
  }
}
export default Header

index.js

import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Component1 from './components/Component1';
import Component2 from './components/Component2';
import Component3 from './components/Component3';
import Component4 from './components/Component4';


class Main extends Component {
    <Router>
        <div>
            <Route exact path='/' component={Component1} />
            <Route path='/ts' component={Component2} />
            <Route path='/cs' component={Component3} />
            <Route path='/cw' component={Component4} />
        </div>
    </Router>
);

export default Main                

1 个答案:

答案 0 :(得分:1)

您的<Link/>组件必须是与<Router/>组件相同的<Route/>组件的子组件。

<Router/>组件中移除<Main/>,并将其放在最近的<Main/><Header/>的祖先中。这将是您的<App/>组件。