React router Link不会导致组件在嵌套路由中更新

时间:2016-08-07 01:04:54

标签: reactjs react-router

这让我发疯了。当我尝试在嵌套路由中使用React Router的链接时,链接会在浏览器中更新,但视图不会更改。然而,如果我将页面刷新到链接,它确实如此。不知何故,组件在应该(或者至少是目标)时不会更新。

这里是我的链接的样子(上一个/下一个项目真的是变种):

<Link to={'/portfolio/previous-item'}>
    <button className="button button-xs">Previous</button>
</Link>
<Link to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>

一个hacky解决方案是manaully调用forceUpate(),如:

<Link onClick={this.forceUpdate} to={'/portfolio/next-item'}>
    <button className="button button-xs">Next</button>
</Link>

这样可行,但会导致整页刷新,我不想要并且出错:

ReactComponent.js:85 Uncaught TypeError: Cannot read property 'enqueueForceUpdate' of undefined

我已经搜索过高低的答案,而我最接近的就是:https://github.com/reactjs/react-router/issues/880。但它已经老了,我没有使用纯渲染混合。

以下是我的相关路线:

<Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio" component={PortfolioDetail} >
        <Route path="/portfolio/:slug" component={PortfolioItemDetail} />
    </Route>
    <Route path="*" component={NoMatch} />
</Route>

无论出于何种原因,调用Link不会导致组件重新安装需要发生的内容,以便获取新视图的内容。它确实调用了componentDidUpdate,我确定我可以检查url slug的变化,然后在那里触发我的ajax调用/视图更新,但似乎不需要这样做。

编辑(更多相关代码):

PortfolioDetail.js

import React, {Component} from 'react';
import { browserHistory } from 'react-router'
import {connect} from 'react-redux';
import Loader from '../components/common/loader';
import PortfolioItemDetail from '../components/portfolio-detail/portfolioItemDetail';
import * as portfolioActions  from '../actions/portfolio';

export default class PortfolioDetail extends Component {

    static readyOnActions(dispatch, params) {
        // this action fires when rendering on the server then again with each componentDidMount. 
        // but not firing with Link...
        return Promise.all([
            dispatch(portfolioActions.fetchPortfolioDetailIfNeeded(params.slug))
        ]);
    }

    componentDidMount() {
        // react-router Link is not causing this event to fire
        const {dispatch, params} = this.props;
        PortfolioDetail.readyOnActions(dispatch, params);
    }

    componentWillUnmount() {
        // react-router Link is not causing this event to fire
        this.props.dispatch(portfolioActions.resetPortfolioDetail());
    }

    renderPortfolioItemDetail(browserHistory) {
        const {DetailReadyState, item} = this.props.portfolio;
        if (DetailReadyState === 'WORK_DETAIL_FETCHING') {
            return <Loader />;
        } else if (DetailReadyState === 'WORK_DETAIL_FETCHED') {
            return <PortfolioItemDetail />; // used to have this as this.props.children when the route was nested
        } else if (DetailReadyState === 'WORK_DETAIL_FETCH_FAILED') {
            browserHistory.push('/not-found');
        }
    }

    render() {
        return (
            <div id="interior-page">
                {this.renderPortfolioItemDetail(browserHistory)}
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}
function mapDispatchToProps(dispatch) {
    return {
        dispatch: dispatch
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(PortfolioDetail);

PortfolioItemDetail.js

import React, {Component} from 'react';
import {connect} from 'react-redux';
import Gallery from './gallery';

export default class PortfolioItemDetail extends React.Component {

    makeGallery(gallery) {
        if (gallery) {
            return gallery
                .split('|')
                .map((image, i) => {
                    return <li key={i}><img src={'/images/portfolio/' + image} alt="" /></li>
            })
        }
    }

    render() {
        const { item } = this.props.portfolio;

        return (
            <div className="portfolio-detail container-fluid">
                <Gallery
                    makeGallery={this.makeGallery.bind(this)}
                    item={item}
                />
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        portfolio: state.portfolio
    };
}

export default connect(mapStateToProps)(PortfolioItemDetail);

gallery.js

import React, { Component } from 'react';
import { Link } from 'react-router';

const Gallery = (props) => {

    const {gallery, prev, next} = props.item;
    const prevButton = prev ? <Link to={'/portfolio/' + prev}><button className="button button-xs">Previous</button></Link> : '';
    const nextButton = next ? <Link to={'/portfolio/' + next}><button className="button button-xs">Next</button></Link> : '';

    return (
        <div>
            <ul className="gallery">
                {props.makeGallery(gallery)}
            </ul>
            <div className="next-prev-btns">
                {prevButton}
                {nextButton}
            </div>
        </div>
    );
};

export default Gallery;

新路线,基于Anoop的建议:

<Route component={App}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio/:slug" component={PortfolioDetail} />
    <Route path="*" component={NoMatch} />
</Route>

5 个答案:

答案 0 :(得分:3)

无法深究这一点,但我能够通过ComponentWillRecieveProps实现我的目标:

componentWillReceiveProps(nextProps){
    if (nextProps.params.slug !== this.props.params.slug) {
        const {dispatch, params} = nextProps;
        PortfolioDetail.readyOnActions(dispatch, params, true);
    }
}

换句话说,无论出于何种原因,当我使用React Router Link链接到具有相同父级组件的页面时,它不会触发componentWillUnMount / componentWillMount。所以我不得不手动触发我的行动。每当我使用不同的父组件链接到Routes时,它确实可以正常工作。

也许这是设计的,但它看起来不对,并不直观。我注意到Stackoverflow上有很多关于链接更改网址但没有更新网页的类似问题,所以我不是唯一的问题。如果有人对此有任何见解,我仍然希望听到它!

答案 1 :(得分:2)

分享组件代码也很好。但是,我尝试在本地重新创建它,并且对我来说工作正常。以下是示例代码

import { Route, Link } from 'react-router';
import React from 'react';
import App from '../components/App';

const Home = ({ children }) => (
  <div>
    Hello There Team!!!
    {children}
  </div>
);

const PortfolioDetail = () => (
  <div>
    <Link to={'/portfolio/previous-item'}>
      <button className="button button-xs">Previous</button>
    </Link>
    <Link to={'/portfolio/next-item'}>
      <button className="button button-xs">Next</button>
    </Link>
  </div>
);

const PortfolioItemDetail = () => (
  <div>PortfolioItemDetail</div>
);

const NoMatch = () => (
  <div>404</div>
);

module.exports = (
  <Route path="/" component={Home}>
    <Route path='/' component={Home}>
        <Route path="/index:hashRoute" component={Home} />
    </Route>
    <Route path="/portfolio" component={PortfolioDetail} />
    <Route path="/portfolio/:slug" component={PortfolioItemDetail} />
    <Route path="*" component={NoMatch} />
  </Route>
);

答案 2 :(得分:1)

我在React 16中也遇到了这个问题。

我的解决方案如下:

componentWillMount() {
    const { id } = this.props.match.params;
    this.props.fetchCategory(id); // Fetch data and set state
}

componentWillReceiveProps(nextProps) {
    const { id } = nextProps.match.params;
    const { category } = nextProps;

    if(!category) {
        this.props.fetchCategory(id); // Fetch data and set state
    }
}

我使用redux来管理状态,但我认为这个概念是一样的。

在WillMount方法上按照正常情况设置状态,当调用WillReceiveProps时,如果状态已经更新,你可以检查状态是否已经更新,你可以回想起设置状态的方法,这应该重新渲染你的组件。

答案 3 :(得分:0)

componentWillReceiveProps是这个的答案,但它有点烦人。我编写了一个BaseController“概念”,它设置路由更改的状态操作,即使路由的组件是相同的。所以想象一下你的路线是这样的:

<Route path="test" name="test" component={TestController} />
<Route path="test/edit(/:id)" name="test" component={TestController} />
<Route path="test/anything" name="test" component={TestController} />

然后BaseController将检查路由更新:

import React from "react";

/**
 * conceptual experiment
 * to adapt a controller/action sort of approach
 */
export default class BaseController extends React.Component {


    /**
     * setState function as a call back to be set from
     * every inheriting instance
     *
     * @param setStateCallback
     */
    init(setStateCallback) {
        this.setStateCall = setStateCallback
        this.setStateCall({action: this.getActionFromPath(this.props.location.pathname)})
    }

    componentWillReceiveProps(nextProps) {

        if (nextProps.location.pathname != this.props.location.pathname) {
            this.setStateCall({action: this.getActionFromPath(nextProps.location.pathname)})
        }
    }

    getActionFromPath(path) {

        let split = path.split('/')
        if(split.length == 3 && split[2].length > 0) {
            return split[2]
        } else {
            return 'index'
        }

    }

    render() {
        return null
    }

}

然后你可以继承那个:

从“反应”中导入React;     从'./BaseController'

导入BaseController
export default class TestController extends BaseController {


    componentWillMount() {
        /**
         * convention is to call init to
         * pass the setState function
         */
        this.init(this.setState)
    }

    componentDidUpdate(){
        /**
         * state change due to route change
         */
        console.log(this.state)
    }


    getContent(){

        switch(this.state.action) {

            case 'index':
                return <span> Index action </span>
            case 'anything':
                return <span>Anything action route</span>
            case 'edit':
                return <span>Edit action route</span>
            default:
                return <span>404 I guess</span>

        }

    }

    render() {

        return (<div>
                    <h1>Test page</h1>
                    <p>
                        {this.getContent()}
                    </p>
            </div>)
        }

}

答案 4 :(得分:0)

我不确定是否可以解决原始问题,但是我遇到了类似的问题,可以通过传入函数回调() => this.forceUpdate()而不是this.forceUpdate来解决。

由于没有其他人提及它,因此我发现您正在使用onClick={this.forceUpdate},并且会尝试使用onClick={() => this.forceUpdate()}