我遵循react-redux的例子:将React Router添加到项目
components/Root.js
import React from 'react';
import { Provider } from 'react-redux';
import App from './App'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Switch>
<Route exact path='/' component={ App }/>
<Route path="/:filter" component={ App }/>
</Switch>
</Router>
</Provider>
);
export default Root;
组件/ Footer.js
import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="all">
All
</FilterLink>
{", "}
<FilterLink filter="active">
Active
</FilterLink>
{", "}
<FilterLink filter="completed">
Completed
</FilterLink>
</p>
)
export default Footer
容器/ FilterLink.js
import React from 'react';
import { NavLink } from 'react-router-dom'
const FilterLink = ({ filter, children }) => {
console.log("filter: "+filter);
console.log("children: "+children);
return (
<NavLink
to={filter === 'all' ? '' : filter}
activeStyle={{
textDecoration: 'none',
color: 'black',
}}
>
{children}
</NavLink>
);
}
export default FilterLink;
我得到的结果是:
根据代码,活动链接应与URL相同。甚至URL显示&#34; localhost:3008 / active&#34;活动链接显示为&#34; all&#34;和类似的完成。
出了什么问题以及为什么相应的链接没有按照URL激活。
答案 0 :(得分:0)
尝试添加/
const FilterLink = ({ filter, children }) => {
console.log("filter: "+filter);
console.log("children: "+children);
return (
<NavLink
// / is added via string interpolation
to={filter === 'all' ? '' : `/${filter}`}
activeStyle={{
textDecoration: 'none',
color: 'black',
}}
>
{children}
</NavLink>
);
}
或
import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="/all">
All
</FilterLink>
{", "}
<FilterLink filter="/active">
Active
</FilterLink>
{", "}
<FilterLink filter="/completed">
Completed
</FilterLink>
</p>
)
export default Footer
并更新FilterLink组件中的检查:
to={filter === '/all' ? '' : filter}