使用Redux的React Router V4无法重新渲染组件

时间:2018-10-23 08:42:53

标签: reactjs react-redux react-router react-router-v4

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

使用以下版本:

"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>组件推送位置,其中connectwithRouter中的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仅被调用一次。

当前行为:

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

我在做什么错了?

1 个答案:

答案 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>