2017-09-17 53 views
0

我提到了许多描述相同问题的链接。其中一些是 herehere。我刚开始做出反应,发现很难理解那里的解释。我遵循教程building react applications with idiomatic redux code。在那里使用的路由器版本是旧的。我更新到4,并得到了这个问题。我的代码如下。NavLink中的ActiveStyle在反应路由器中无法正常工作

const Root = ({ store }) => (
    <BrowserRouter> 
     <Provider store={store}> 
      <Route path="/:filter?" component={App} /> 
     </Provider> 
    </BrowserRouter> 
); 

class App extends Component { 
    render() { 
     return (
      <div> 
       <AddTodo /> 
       <VisibleTodoList /> 
       <Footer location={this.props.location}/> 
      </div> 
     ); 
    } 
} 

const Footer = ({ location }) => (
    <p> 
     Show :{" "} 
     <FilterLink location={location} filterValue="all"> 
      All 
     </FilterLink>{" "} 
     <FilterLink location={location} filterValue="active"> 
      Active 
     </FilterLink>{" "} 
     <FilterLink location={location} filterValue="completed"> 
      Completed 
     </FilterLink> 
     </p> 
); 

const FilterLink = ({ filterValue, children, location }) => { 
    return (
     <NavLink 
      to={filterValue === "all" ? "" : filterValue} 
      activeStyle={{ textDecoration: "none", color: "red" }} 
     > 
      {children} 
     </NavLink> 
    ); 
}; 

此代码使浏览器中的url相应地改变。但风格不更新。对于所有操作,链接“全部”是红色的。

我的理解是,通过位置道具(根据解释here)将使组件重新渲染,风格将得到更新(如果我在这里错了,请更正)。但它没有发生。有人可以帮助我吗?

回答

2

我想出了这个错误。问题就出在这里

const FilterLink = ({ filterValue, children }) => { 
    return (
     <NavLink 
      exact 
      to={filterValue === "all" ? "/" : `/${filterValue}`} 
      activeStyle={{ textDecoration: "none", color: "red" }} 
     > 
      {children} 
     </NavLink> 
    ); 
}; 

"to"道具必须在一开始,如上图所示设置有"/"

我错过了这一点。这解决了我的问题。也不需要传递位置道具。在教程中,他在FilterLink组件中没有使用“/”。由于我使用的是新版本,代码无效。