在推送新位置时,我在渲染组件时遇到困难。
使用以下版本:
"react": "^16.5.2", "react-router-dom": "^4.3.1", "redux": "^4.0.0"
Base.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
用withRouter
中的react-router-dom
包裹:(export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));
)
var route = "/service/details/" + value
this.props.history.push(route)
子组件(ServiceDetails.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);
该链接已在浏览器的网址栏中正确更新,但未呈现该组件。此外,整个应用程序加载时,子组件的componentWillReceiveProps
仅被调用一次。
当前行为:
Service details: 5
Service details: 5
我在做什么错了?
答案 0 :(得分:1)
您的标头组件不在路由器提供商组件中,请将标头包装在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>