从共享组件库中导出`react-router`重定向

Cor*_*rey 9 javascript npm reactjs webpack react-router

我有一个正在构建的共享(反应)组件库。PrivateRoute我想包含一个组件。但是,当我将组件从模块库导入另一个应用程序时,出现错误:

错误:不变式失败:您不应在<Router>外使用<Redirect>

PrivateRoute组件react-router/Route使用身份验证逻辑包装该组件,并将未经身份验证的请求重定向到登录:

组件库

import { Route, Redirect } from 'react-router';
/* ... */

class PrivateRoute extends Component {
  /* ... */
  render() {
    const {
      component: Comp, authState, loginPath, ...rest
    } = this.props;

    return (
      <Route
        {...rest}
        render={props => authState === SIGNED_IN ? (
          <Comp {...props} />
        ) : (
          <Redirect
            to={{
              pathname: loginPath,
            }}
          />
        )}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,我将组件导入到一个单独的(反应)项目中:

创建反应应用

import { Router } from 'react-router';
import { PrivateRoute } from 'component-library';
/* ... */

class App extends Component {
  // "history" is passed in via props from the micro frontend controller.
  /* ... */

  render() {
    return (
      <Router history={this.props.history}>
        {/* ... */}
        <PrivateRoute path="/protected" component={ProtectedView} />
      </Router>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果PrivateRoutecreate-react-app应用程序中定义了组件,这将按预期工作。但是,将此组件移到共享库会导致错误。

我尝试用webpack输出libraryTarget设置为commonjs2来构建库。但是,我也尝试过umd。我也尝试过汇总。所有结果相同。

webpack.config.js

module.exports = {
  //...
  output: {
    path: path.resolve(__dirname, 'dist/'),
    publicPath: '',
    filename: '[name].js',
    libraryTarget: 'commonjs2',
  },
  //...
};
Run Code Online (Sandbox Code Playgroud)

我的假设是问题在于构建组件库,因为当Redirect找不到时会抛出Invariant错误RouterContext。尽管该库的构建没有错误,但导入已编译/构建的代码似乎是一个问题。

也可能是React的两个实例,导致Context API出现问题。但是,react-router没有使用Context API。它使用的是mini-create-react-contextpolyfill。

有关如何解决此问题的任何想法或想法?

Cor*_*rey 1

我终于发现了这个与 无关react-router而更多的问题React。我发现此错误只会在本地开发中显示,因为它component-library是通过npm link.

该决议来自这个答案:/sf/answers/2717285091/

我的解决方案是将组件库中的 React 和 React Router 链接到 React 和 React Router 的应用程序引用:

# link the component library
cd my-app
npm link ../component-library

# link its copy of React back to the app's React
cd ../component-library
npm link ../my-app/node_modules/react
npm link ../my-app/node_modules/react-router
Run Code Online (Sandbox Code Playgroud)