我正在尝试使用React-Router V4向我的应用添加路由,但它根本不起作用。基本上,我正在尝试使用history.push
以编程方式更改路径,这会更新浏览器URL,但不会更改实际应用内的任何内容。
注意:我使用的是redux。
关于这个问题,唯一回答的问题是:
React history.push() is updating url but not navigating to it in browser
但是,我已经尝试了上述问题的答案,但这对我不起作用。
以下是重要的片段:
最顶层文件(index.js)
...
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App/>
</Provider>
</BrowserRouter>
, document.getElementById('root'));
...
包含路线的组件
...
export default function ContentRouter() {
return <div className="content">
<Route exact path="/dashboard" component={TmpDashboard}/>
<Route exact path="/" component={() => {
return <h1>Home</h1>
}}/>
</div>
}
组件推送路线
...
this.handleGroupClick = (group) => {
this.props.history.push(`/groups/${group}`);
this.props.onOpenChange(false);
};
...
export default withRouter(connect(mapStateToProps, mapDispatchToProps(DrawerConnector))
答案 0 :(得分:10)
在完全错误的地方进行了大量搜索之后,我发现了什么是错的。缺乏更新是由 Redux
引起的每当组件被connect
包裹时,都会导致更新被阻止,并且视图不会更新。
这里提到了解决方案:
https://github.com/ReactTraining/react-router/issues/4671#issuecomment-285320076
基本上,其中包含Route
或React-Router事物的每个组件都必须用withRouter
编辑:只有使用connect
的顶级组件才应包含在withRouter
中。请注意,这可能会导致性能问题
编辑:我解决增加耦合的方法是有一个组件来处理路由。这样,我只需要包装该组件,并将组件包含在路由器中。
答案 1 :(得分:0)
这是一个有效的设置:
主要应用:
from collections import defaultdict
my_dict = defaultdict(list)
my_list = ['A', ['A', 1], ['A',2], 'B', ['B',1], ['B',2], 'C', ['C', 1], ['C',2]]
for index in my_list:
if len(index) > 1:
my_dict[index[0]].append(index)
CommonComponentThatPushesToHistory
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
/* this is a common component and happens to need to redirect */
<Route component={CommonComponentThatPushesToHistory} />
<div id="body">
/* I usually place this switch in a separate Routes file */
<Switch>
<Route exact path="FooRoute" component={FooPage}/>
<Route exact path="BarRoute" component={BarPage}/>
</Switch>
</div>
/* another common component which does not push to history */
<Footer />
</div>
</BrowserRouter>
);
}
}
export default withRouter(App);
FooPage可能有一个推送历史记录的子组件:
class CommonComponentThatPushesToHistory extends React.Component{
render(){
return(
<button type="button"
onClick={() => {this.props.history.push('some-page');}}>
Click to get redirected</button>
);
}
}
然后MyChild组件可以像CommonComponentThatPushesToHistory一样推送到历史记录。
答案 2 :(得分:-4)
您可以使用Redirect组件+状态,在react-router V4中重定向。