带有 redux 的 React 路由器 v4 无法重新渲染组件



在推送新位置时,我在渲染组件时遇到困难。

使用这些版本:

"react": "^16.5.2",
"react-router-dom": "^4.3.1",
"redux": "^4.0.0"

基地.js

<div >
<Header />
<div id="contentwrapper">
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/service/details/:id' render={(props) => (
<ServiceDetails key={props.match.params.id} {...props} />)
} />
</Switch>
</BrowserRouter>
</div>
<Footer id="footer" />
</div>

我如何推动位置:

该位置正在从组件推送<Header>其中connect用来自react-router-domwithRouter包裹:(export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));(

var route = "/service/details/" + value        
this.props.history.push(route)

子组件(服务详细信息.js(

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import _ from 'lodash';
import { getServiceDetailsAction } from '../actions/ServiceActions';
import { getServiceDetails } from '../requests/ServiceAxios';
class ServiceDetails extends React.Component {
// constructor
componentWillReceiveProps(newProps) {
debugger;
}
render() {
return (
<div>
Service details: {this.props.location.pathname.substring(this.props.location.pathname.lastIndexOf('/') + 1)}
</div>
)
}
}
function mapStateToProps(state) {
return {
serviceStore: state.ServiceReducer
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
getServiceDetailsAction: getServiceDetailsAction
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ServiceDetails);

链接在浏览器的 url 栏中正确更新,但组件未呈现。此外,子组件的componentWillReceiveProps仅在加载整个应用时调用一次。

当前行为:

  • this.props.history.push("/service/details/5"(
  • 页面呈现Service details: 5
  • this.props.history.push("/service/details/262"(
  • 页面仍显示Service details: 5

我做错了什么?

您的标头组件不在路由器提供程序组件中,请将标头包装在BrowserRouter组件中

<BrowserRouter>
<div >
<Header />
<div id="contentwrapper">
<Switch>
<Route exact path='/' component={Home} />
<Route path='/service/details/:id' render={(props) => (
<ServiceDetails key={props.match.params.id} {...props} />)
} />
</Switch>
</div>
<Footer id="footer" />
</div>
</BrowserRouter>

最新更新