使用相同的组件用于不同的路由与反应路由器

问题描述:

我有一个PageBuilder组件,根据配置文件动态构建编辑/列表页面。我想要使​​用相同的PageBuilder组件的动态路由(如“/ collection/list”,“/ collection/edit/123123”,“/ dashboard”等)。 我无法正常工作 - 例如,如果我在/收藏/列表中,点击链接到/ collection/edit/1231时不起作用。只有对该URL的刷新才有效(反之亦然)。 我试着把我的初始化代码PageBuilder的componentWilLReceiveProps,但它似乎每秒钟都会调用它。 我的路线是这样的: <Route path="/" component={App}> <IndexRedirect to="/dashboard" /> <Route path="/:page/:collection/:action(/:entity_id)" component={PageBuilder} /> <Route path="/:page" component={PageBuilder} /> </Route> 使用相同的组件用于不同的路由与反应路由器

而且我PageBuilder:

constructor(props) { 
    super(props); 
    this.createSectionsHTML = this.createSectionsHTML.bind(this); 
    this.onChange = this.onChange.bind(this); 
    this.onSave = this.onSave.bind(this); 
} 

getPageName() { 
    return this.props.params.page.replace(/-/g, '_').toLowerCase(); 
} 

componentWillReceiveProps(props) { 
    this.action = this.props.params.action; 
} 

componentWillMount() { 
    let pageName = this.getPageName(); 
    this.props.dispatch(setInitialItem(pageName)); 
} 

componentDidMount() { 

    let pageName = this.getPageName(); 
    let { collection, entity_id } = this.props.params; 

    if (collection && entity_id) { 
     let { dispatch } = this.props; 
     dispatch(getCollectionEntity(collection, entity_id, pageName)); 
    } 
} 

如何给每个我重定向到一个不同的路线时重新渲染页面的任何想法?如果我可以在重定向时卸载并重新安装组件,那将是非常好的,但我不知道如何去告诉React Router这样做......

谢谢!

使this.state这样它将控制你的组件如何呈现。

现在,内componentWillReceiveProps,检查nextProps参数

componentWillReceiveProps(nextProps, nextState) { 
    if(<check in nextProps if my route has changed>) { 
    let newState = Object.assign({}, this.state); 
    // make necessary changes to the nextState Object by calling 
    // functions which would change the rendering of the current page 
    this.setState({ nextState }); 
    } 
} 

这将使componentWillReceiveProps采取行动路线的变化,只有当。

在渲染功能

现在,

render() { 
    const { necessary, variables, to, render } = this.state; 
    let renderVariables = this.utilityFunctionsReqToRender(someArgs); 
    return (
    <toRenderJsx> 
     ... 
    </toRenderJsx> 
) 
} 

这将使你的组件“刷新”每当路由变化。

+0

谢谢!我的页面构建器的工作方式并不是真的依赖''this.state'',但我可以改变它,以便它(我为我的应用程序范围使用Redux)。我用这种方法遇到的另一个问题是,我知道我的位置何时更改,但是如果我要刷新页面,我无法知道我“更改了”路线(因为“nextProps”和“ this.props''显然是相同的...) 但我会尝试玩这个解决方案,我认为这是一个很好的起点。谢谢! – user1595077

+0

很酷,我通过改变渲染来更多地依赖''this.state''来获得这个工作(呃,有一些小问题,但路由工作!)。谢谢! – user1595077