react-router-v4 NavLink不重新渲染组件

时间:2018-05-11 19:57:03

标签: reactjs react-router react-router-v4

使用react路由器2,单击“链接”组件将触发组件的重新渲染。

我正在使用“NavLink”而不是“Link”将我的项目转换为路由器4。除此之外一切正常:单击“NavLink”不会重新渲染我的组件(更新我的待办事项列表),它只会更改链接。

我是否应该在某处添加任何内容以使其工作?它与反应路由器2“链接”完全正常。

以下是示例代码:

App.js:

const App = ({ match: { params } }) => {
  return (
    <div>
      <AddTodo />
      <VisibleTodoList filter={params.filter || 'all'} />
      <Footer />
    </div>
  )
}

Footer.js:

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

Filterlink.js:

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

VisibleTodoList.js:

const mapStateToProps = (state, ownProps) => {
  return {
    todos: getVisibleTodos(
        state.todos,
        ownProps.filter
    ),
  };
};

const mapDispatchToProps = (dispatch) => ({
    onTodoClick(id) {
        dispatch(toggleTodo(id))
    },
});

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList);

2 个答案:

答案 0 :(得分:1)

v4中没有params个道具,好吧,不像过去那样,

你必须改变一些事情。

App.js

// imports

import {withRouter} from 'react-router'

// ...

let App = ({ match }) => ( // change params to match
  return (
    <div>
      <AddTodo />
      <VisibleTodoList filter={match.params.filter || 'all'} />
      <Footer />
    </div>
  )
}

App = withRouter(App)

请记住,如果您想将react-redux connect HOC添加到App.js,则必须使用connect()包裹withRouter()

App = withRouter(connect()(App))

然后导入App

import {Router} from 'react-router'
import createHistory from 'history/createBrowserHistory'
import App from './path/to/App'

// ...

<Router history={createHistory()}>
   <App />
</Router>

答案 1 :(得分:0)

感谢@kiarashws

需要在单独的组件内传递路径:

const MyRoutes = () => (
    <Route path='/:filter?' component={App} />
);
render(
    <Provider store={store}>
          <Router>
              <MyRoutes/>
          </Router>
    </Provider>,
    document.getElementById('root')
)

如果不是&#34; MyRoutes&#34;我直接通过该路线,NavLink不会触发Todos更新。那么为什么路线需要在一个单独的组件中?