【发布时间】:2018-02-19 15:51:45
【问题描述】:
我将 React Router Dom 4.2.2 与 Redux 一起使用,但我无法使 <Link> 正常工作。按下链接时,URL 会更改,但内容不会刷新/呈现。我正在使用withRouter(connect(..., ...))(Component),但仍然无法正常工作。
这是组件:
class IndexPage extends React.Component {
constructor(props) {
console.log(props.location.state);
super(props);
this.state = {
display: (props.location.state && props.location.state.display) ? props.location.state.display : null
};
}
componentDidMount() {
console.log("[LOADED]IndexPage");
const self = this;
}
render() {
const self = this;
var displayBlock;
switch (this.state.display) {
case 'SPORT':
displayBlock = <SportElement/>
break;
default:
displayBlock = (
<div className="container">
<div className="row">
<div style={ styles.xal_item_container } className="col-lg-2 col-md-3 col-sm-3 col-6">
<Link style={ Object.assign({}, styles.xal_item, styles.xal_red) } to={{
pathname: '/sport',
state: {
display: 'SPORT'
}
}}>
<div><i style={ styles.xal_icon } className="fa fa-money fa-5x"></i></div>
<div style={ styles.xal_title }>Sport</div>
</Link>
<Link to='/gg'>QWDWD</Link>
</div>
<div style={ styles.xal_item_container } className="col-lg-2 col-md-3 col-sm-3 col-6">
<div style={ Object.assign({}, styles.xal_item, styles.xal_red) }>
<div><i style={ styles.xal_icon } className="fa fa-money fa-5x"></i></div>
<div style={ styles.xal_title }>Crawler</div>
</div>
</div>
</div>
</div>
);
}
return (
<div className="container-fluid">
<div className="row">
<div style={ Object.assign({}, styles.xal_topBar, styles.no_margin) } className="col">
wwefwefe
</div>
</div>
<br/>
<div className="row">
<div className="col">
{ displayBlock }
</div>
</div>
</div>
);
}
};
function mapStateToProps(state) {
return {
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
}, dispatch);
}
export default withRouter(connect(mapStateToProps, matchDispatchToProps)(IndexPage))
这里是 App.js 中的<Switch>:
import React from 'react';
import { Router, Redirect } from 'react-router';
import { browserRouter, Switch, Route } from 'react-router-dom'
import IndexPage from 'components/Pages/IndexPage.react'
export default class App extends React.Component {
render() {
return (
<Switch>
<Route exact path="/" component={IndexPage}/>
<Route exact path="/sport" component={IndexPage}/>
<Redirect from='*' to='/' />
</Switch>
);
}
}
【问题讨论】:
-
你需要将你的 App 组件放在单个 Router 组件中。
-
抱歉,您需要将应用组件包装在 WithRouter 而不是 indexpage 中。请忽略以上评论
-
export default withRouter(App);不起作用
标签: reactjs redux react-router react-redux react-router-v4