使用与React Router相同的组件用于不同的路由

时间:2016-04-24 10:50:26

标签: javascript reactjs react-router

我有一个PageBuilder组件,可以根据配置文件动态构建编辑/列表页面。我想要使​​用动态路线(例如&#34; / collection / list&#34;,&#34; / collection / edit / 123123&#34;,&#34; / dashboard&#34;等)相同的PageBuilder组件。 我无法让它工作 - 如果我在/ collection / list中,例如,点击指向/ 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这样做....

谢谢!

2 个答案:

答案 0 :(得分:8)

使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>
  )
}

只要路线发生变化,这将使您的组件“刷新”。

答案 1 :(得分:0)

  从React 16.3.0开始不推荐使用

componentWillReceiveProps   (如浏览器控制台中的警告所述)

参考:     https://reactjs.org/docs/react-component.html#componentdidupdate

因此 componentDidUpdate 可以用来获取新状态并根据参数重新加载数据

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate " +prevState.id);
    reloadData(prevState.id);
}