【发布时间】:2026-01-11 00:20:03
【问题描述】:
如果我想从"react-router": "^2.0.0" 升级到"react-router": "^4.0.0","react-router-dom": "^4.0.0"。
我的结构应该是这样的:
- 主组件:是所有事物的容器组件( 父母)。
- 导航组件:用于在我的其他子组件之间导航,该组件应始终出现。
- 子组件:示例、关于、测试。其中 Test 是默认值。
我的旧代码按预期工作是这样的:
-App.jsx
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Main}>
<Route path="about" component={About}/>
<Route path="examples" component={Examples}/>
<IndexRoute component={Test}/>
</Route>
</Router>,
document.getElementById('app')
);
-主要组件是这样的:
var React = require('react');
var Nav = require('Nav');
var Main = (props) => {
return (
<div>
<Nav/>
{props.children}
</div>
);
}
module.exports = Main;
-我的导航组件是这样的:
var React = require('react');
var {Link, IndexLink} = require('react-router');
var Nav = () => {
return (
<div>
<IndexLink to="/" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Test</IndexLink>
<Link to="/about" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>About</Link>
<Link to="/examples" activeClassName="active" activeStyle={{fontWeight: 'bold'}}>Examples</Link>
</div>
);
};
module.exports = Nav;
我尝试这样升级:
-App.jsx
var { BrowserRouter, Route } =require('react-router-dom');
ReactDOM.render(
<BrowserRouter>
<div>
<Route path='/' component={Main} />
<Route path='/Test' component={Test}/>
<Route path='/about' component={About}/>
<Route path='/examples' component={Examples}/>
</div>
</BrowserRouter>,
document.getElementById('app')
);
-我的主要组件没有变化
-我的导航组件是这样的:
var React = require('react');
var {Link, NavLink} =require('react-router-dom');
var Nav = ()=>{
return(
<div>
<NavLink activeClassName="active" activeStyle={{fontWeight: 'Bold'}} to="/Test">Test</NavLink>
<NavLink activeClassName="active" activeStyle={{fontWeight: 'Bold'}} to="/about">About</NavLink>
<NavLink activeClassName="active" activeStyle={{fontWeight: 'Bold'}} to="/examples">Examples</NavLink>
</div>
);
}
module.exports = Nav;
我面临以下问题:
- 测试组件不像以前那样默认了。
- 主组件的行为不像父组件。
- 在示例中刷新浏览器时,出现以下错误:
http://localhost:5000/examplesnet::ERR_CONNECTION_REFUSED
【问题讨论】:
标签: javascript reactjs react-router jsx react-dom