我使用的是react-router-dom 4.0.0。当我点击按钮时,url会改变,但页面不会改变,我必须刷新页面才能转到新页面。
render() {
return (
<div className='text-xs-right' >
<Link to="/posts/new" >
<button type="button" className="btn btn-primary" > Add a Post </button>
</Link>
</div>
);
}这是我的路由器:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers';
import PostsIndex from './components/postsIndex';
import NewPost from './components/newPost';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router>
<div>
<Route exact path={'/'} component={PostsIndex} />
<Route exact path={'/posts/new'} component={NewPost} />
</div>
</Router>
</Provider>
, document.querySelector('.container'));下面是我的依赖项:
"dependencies": {
"axios": "^0.18.0",
"babel-preset-stage-1": "^6.1.18",
"lodash": "^3.10.1",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-redux": "4.3.0",
"react-router": "^2.0.1",
"react-router-dom": "^4.0.0",
"redux": "^3.0.4",
"redux-promise": "^0.5.3"
}我找到了一个解决方案,但仍然不知道为什么我之前的代码不能工作。不过,下面的代码可以正常工作:
<Switch>
<Route path={'/posts/new'} component={NewPost} />
<Route path={'/'} component={PostsIndex} />
</Switch>
为什么我的第一种方法不起作用?
发布于 2018-03-20 06:06:36
好的,我找到了一个解决方案,我只需要更新我的包来:
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",现在,无需刷新页面即可正常工作:
<Router>
<div>
<Route exact path={'/'} component={PostsIndex} />
<Route exact path={'/posts/new'} component={NewPost} />
</div>
</Router>发布于 2018-03-20 11:25:10
发生这种情况的原因是Switch匹配它找到的第一个匹配路由。在你的例子中,当/在/posts/new之上时,发生的事情是/也匹配/posts/new,所以它呈现/,而不检查其余的。当你把它放在相反的顺序时,当链接是/posts/new时,它首先匹配它,而不检查/,所以你得到了正确的结果。
或者,您可以传递exact prop,以便只有在准确的情况下,它才会与链接匹配。然后你就可以写
<Switch>
<Route path={'/'} exact component={PostsIndex} />
<Route path={'/posts/new'} component={NewPost} />
</Switch>现在,只有当链接完全为/时,才会匹配/,因此您将获得预期的结果。
假设路径为/one,location.pathname为/one/two。如果exact为false,则路径/one将与/one/two匹配,而如果exact为true,则不匹配。
https://stackoverflow.com/questions/49372927
复制相似问题