【问题标题】:props.history.push inside functional component renders doesn't render the component功能组件渲染中的 props.history.push 不会渲染组件
【发布时间】:2020-03-26 03:16:40
【问题描述】:

我正在使用上下文 API,在我的 AuthContextProvider 中我有一个函数,我调用它然后更改路由;问题是它更改了路由但不渲染组件,我不知道为什么。我相信如果我将 auth-context.js 类转换为基于类的类,它会起作用。

我尝试返回 Redirect to ="/ /> 但这不起作用。 我很难过。如果有人可以帮忙,我会很高兴

auth-context.js
import React, { useState } from 'react';
import { withRouter, Redirect } from 'react-router-dom';
import axios from 'axios';
export const AuthContext = React.createContext({
  isAuth: false,
  login: () => {},
  seedFirebase: () => {}
});

const AuthContextProvider = props => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  console.log(props);
  const loginHandler = () => {
    setIsAuthenticated(true);
    props.history.push('/'); //this changes the route but does not render the component
  };
  //THIS FUNCTION SEEDS THE FIREBASE DATABASE
  const seedDb = () => {
    const data = {
      items: 'Folders'
    };
    // axios.post('/items.json', data).then(resp => console.log(resp.data));
  };
  return (
    <AuthContext.Provider
      value={{
        login: loginHandler,
        isAuth: isAuthenticated,
        seedFirebase: seedDb
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};
export default withRouter(AuthContextProvider);

【问题讨论】:

    标签: reactjs react-router react-context


    【解决方案1】:

    一个简单的解决方案是在源目录的 helper 文件夹中创建一个 history.js 文件。 在 history.js 文件中添加以下代码。

    import { createBrowserHistory } from 'history';
    export default createBrowserHistory();
    

    然后将history.js文件导入到你需要的以下文件中。

    import history from '/helpers/history';
    

    然后使用history.push('/') 重定向到home 组件。

    希望这会有所帮助!

    【讨论】:

    • 您好,感谢您的回复,不幸的是它仍然是同一个问题 - 它改变了路线,但组件永远不会被渲染
    • 你有吗像这样在 App.js 中添加路由?
    【解决方案2】:

    发布此内容以防其他人遇到此特殊问题。我使用以下逻辑解决了这个问题:我签入调用登录函数的组件,如果isAuthenticated 为真,我将重定向到主页。

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 2019-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多