2017-09-17 49 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組件中沒有使用「/」。由於我使用的是新版本,代碼無效。