【问题标题】:props.history.push() not working in metronic themeprops.history.push() 在 metronic 主题中不起作用
【发布时间】:2021-02-04 10:08:17
【问题描述】:

登录后,我没有重定向到我的用户页面,我使用的是 react metronic 主题。 我认为 props.history.push() 有问题 这是我到目前为止所做的。

主要组件如下:

ReactDOM.render(
  <MetronicI18nProvider>
    <MetronicLayoutProvider>
      <MetronicSubheaderProvider>
        <MetronicSplashScreenProvider>
          <ToastContainer/>
          <App store={store} persistor={persistor} />
        </MetronicSplashScreenProvider>
      </MetronicSubheaderProvider>
    </MetronicLayoutProvider>
  </MetronicI18nProvider>,
  document.getElementById("root")
);

应用组件:

export default function App({ store, persistor }) {
  return (
    /* Provide Redux store */
    <Provider store={store}>
      {/* Asynchronously persist redux stores and show `SplashScreen` while it's loading. */}
      <PersistGate persistor={persistor} loading={<LayoutSplashScreen />}>
        {/* Add high level `Suspense` in case if was not handled inside the React tree. */}
        <React.Suspense fallback={<LayoutSplashScreen />}>
          {/* Override `basename` (e.g: `homepage` in `package.json`) */}
          <BrowserRouter>
            {/*This library only returns the location that has been active before the recent location change in the current window lifetime.*/}
            <MaterialThemeProvider>
              {/* Provide `react-intl` context synchronized with Redux state.  */}
              <I18nProvider>
                {/* Render routes with provided `Layout`. */}
                <Routes />
              </I18nProvider>
            </MaterialThemeProvider>
          </BrowserRouter>
        </React.Suspense>
      </PersistGate>
    </Provider>
  );
}

这是我的路由器组件

   <Switch>
            {getToken()==null? (
                <Route>
                    <AuthPage/>
                </Route>
            ) : (
                <Redirect from="/auth" to="/"/>
            )}

            <Route path="/error" component={ErrorsPage}/>

            {getToken()==null ? (
                <Redirect to="/auth/login"/>
            ) : (
                <Layout>
                    <BasePage/>
                </Layout>
            )}
        </Switch>

这是我的基础组件

export default function BasePage() {
    return (
        <Suspense fallback={<LayoutSplashScreen/>}>
            <Switch>
                <Redirect exact from="/" to="/allUsers"/>
                <ContentRoute path="/allUsers" component={AllUsers}/>
                <Redirect to="error/error-v1"/>
            </Switch>
        </Suspense>
    );
}

这是我在登录按钮后触发的操作

 props.onLogin(values).then((res) => {
            toast.success('Login Successfull')
            props.history.push('/allUsers')
        }).catch((err) => {
            console.log('error', err)
            toast.error('Login failed')
        })

我有相同的 AuthPage 组件。

api 完全触发成功,token 保存成功,toaster 显示“登录成功”。但我没有重定向到我想要的页面。 但如果我刷新,我会被重定向到主页。

谁能帮我解决这个问题

** history.push 在/allUsers 路由中工作。但不能在登录组件中工作

更新:我想我发现我做错了。 当我保存令牌时(这是我在 onLogin 操作中所做的),我不需要执行任何 history.push() 操作,它应该自动重定向到 AllUsers 页面。 我将方法更改为如下,现在它正在工作。

  const {isAuthorized} = useSelector(
        ({mainAuth}) => ({
            isAuthorized: mainAuth.user != null,
        }),
        shallowEqual
    );

replaced getToken with isAuthorized

但 history.push() 在这里不起作用仍然是个谜。

【问题讨论】:

  • 如果不需要状态持久化你也可以使用window.location.href = '/allUsers'重定向
  • 可以,但我想知道上面的代码有什么问题
  • 如果你可以在codesandbox上发布一个可重现的demo或者分享一个github仓库我可以看看,但是这里没有足够的代码来弄清楚发生了什么。
  • 你在使用customHistory吗?
  • 你找到解决办法了吗!?

标签: reactjs redux react-router-dom metronic


【解决方案1】:

我认为在您的情况下,您没有在道具中获得历史参考。您可以尝试这两种解决方案。 withRouter 来自react-router & useHistory 来自react-router-dom

import { withRouter } from 'react-router'; 
componentName(){
   const { match, location, history } = this.props
    history.push('Your Page')
}
export default withRouter(componentName);

OR

import { useHistory } from "react-router-dom";

component(){
    const history = useHistory();
    history.push('Your Page')
}

【讨论】:

  • 我在道具中获得了历史。但 history.push 不起作用
  • 代码不足以理解发生了什么问题。如果可能,请分享 Github 存储库,以便我们进行调试。
  • @AbhishekYadav 你试过 useHistory 和 withRouter 吗?
【解决方案2】:

react-router v5.2.0 的历史包版本请使用 v4.9.0

工作示例 https://codesandbox.io/s/quizzical-dan-z3725

最初在这里回答:https://stackoverflow.com/a/64623542/1723410

【讨论】:

  • 我正在使用 react-router-dom
【解决方案3】:

试试这个

import { useHistory } from "react-router-dom";

export someclass/ReactComponent{
.
.
.
const history = useHistory();

 props.onLogin(values).then((res) => {
            toast.success('Login Successfull')
            history.push('/allUsers')
        }).catch((err) => {
            console.log('error', err)
            toast.error('Login failed')
        })
}
}

或参考this thread

【讨论】:

    【解决方案4】:

    我想我已经能够重现您的问题here,但还不确定解决方案。但我的猜测是,当你执行 history.push 时,你的 root 大多数 Switch 不会被触发,所以那些带有 getToken 的表达式不会被评估,这就是为什么我们没有被重定向到任何地方。

    如果我以后有时间玩更多,我可能会更新这个答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多