如果我想从 "react-router": "^2.0.0"
升级到 "react-router": "^4.0.0","react-router- dom": "^4.0.0"
.
我的结构应该是这样的:
- 主要组件:是所有事物的容器组件( parent )。
- Nav 组件:用于在我的其他子组件之间导航,该组件应始终显示。
- 子组件:示例、关于、测试。其中 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;
我面临以下问题:
- 测试组件不像以前那样默认。
- 主组件的行为不像父组件。
- 当我在 Examples 上刷新浏览器时,出现以下错误:
http://localhost:5000/examples net::ERR_CONNECTION_REFUSED
最佳答案
所以你需要更改你的 App.jsx 模块,所以它只渲染主要组件,因为现在你可以将你的路由器移到那里。 React Router v4 不再将它的路由渲染到 props children。现在您需要在您希望它呈现的特定位置声明它。
应用程序.jsx
ReactDOM.render(
<Main/>,
document.getElementById('app')
);
主要成分
var React = require('react');
var Nav = require('Nav');
var { HashRouter, Route, Switch } = require('react-router-dom');
var Main = (props) => {
return (
<HashRouter>
<Nav/>
<Switch>
<Route path='/about' component={About}/>
<Route path='/examples' component={Examples}/>
<Route component={Test}/>
</Switch>
</HashRouter>
);
}
module.exports = Main;
- 现在您的 Main 组件可以像父组件一样运行。
- 如果您删除 Route 组件的路径属性,它将表现得像默认的一样。您可能还注意到我添加了 Switch 组件。它应该确保只呈现一条路线。您可以在manual中查看详细信息.
- 之前,您为路由器使用了 hashHistory,现在您可以使用 HashRouter 来做同样的事情。这应该可以解决您遇到的错误。
关于javascript - 如何从 react-router 升级到 react-router-dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685531/