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

Using the same component for different Routes with React Router

我有一个 PageBuilder 组件,它根据配置文件动态构建 edit/list 页面。我想要使​​用相同 PageBuilder 组件的动态路由(如“/collection/list”、“/collection/edit/123123”、“/dashboard”等)。

我无法让它工作 - 例如,如果我在“/collection/list”中,当点击 link 到“/collection/edit/1231”时没有工作。只有刷新 URL 有效(反之亦然)。

我试着把我的初始化代码放在 PageBuildercomponentWilLReceiveProps 但它似乎每秒都会调用它。

我的路线是这样的:

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

每当路线改变时,这将使您的组件 "refresh"。

componentWillReceiveProps is deprecated since React 16.3.0 (as says a warning in the browser console)

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

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

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