我有一个正在构建的共享 (React) 组件库。我想包含一个 PrivateRoute
组件。但是,当我将模块库中的组件导入另一个应用程序时,出现错误:
Error: Invariant failed: You should not use <Redirect> outside a <Router>
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,
}}
/>
)}
/>
);
}
}
然后我将组件导入到一个单独的 (React) 项目中:
创建 react 应用
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>
);
}
}
如果在 create-react-app 应用程序中定义了 PrivateRoute
组件,这将按预期工作。但是,将此组件移动到共享库会导致错误。
我已经尝试构建库,并将 webpack 输出 libraryTarget
设置为 commonjs2。但是,我也尝试过 umd。我也尝试过 Rollup。结果都一样。
webpack.config.js
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '',
filename: '[name].js',
libraryTarget: 'commonjs2',
},
//...
};
我的假设是问题出在构建组件库上,因为当 Redirect
无法找到 RouterContext
时会抛出 Invariant 错误。尽管库构建没有错误,但导入编译/构建的代码似乎是个问题。
也可能是 React 的两个实例导致 Context API 出现问题。但是,react-router
没有使用 Context API。它使用 mini-create-react-context
polyfill。
关于如何解决这个问题有什么想法或想法吗?
最佳答案
您必须从 react-router-dom 导入路由器(假设您使用的是 V4),例如:
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
In v4, react-router exports the core components and functions. react-router-dom exports DOM-aware components, like <Link> (which renders an <a>) and <BrowserRouter> (which interacts with the browser's window.history ).
react-router-dom re-exports all of react-router's exports, so you only need to import from react-router-dom in your project.
引用:https://github.com/ReactTraining/react-router/issues/4648#issuecomment-284479720
关于javascript - export `react-router` 从共享组件库重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708153/