ReactJS TypeError:无法读取未定义的属性“ push”

时间:2020-01-02 08:07:15

标签: reactjs react-router push navigateurl

我构建自己的Apps并学习ReactJS

到目前为止,我的代码错误,我尝试在Internet和论坛上进行搜索,但无法修复。 这是我的代码:

logout(){
    localStorage.removeItem("token");
    localStorage.clear();
    if(localStorage.getItem('token') === null){
        this.props.history.push('/login')
    }
}

错误: TypeError:无法读取未定义的属性“ push”

请帮助我

3 个答案:

答案 0 :(得分:1)

我的猜测是您的logout位于一个本身不是Route的组件内。 那就是我的意思是你不是在<Route path="/" component={ComponentThatHasLogoutMethod} />

仅用作Route的组件具有history属性。 如果需要其他嵌套组件中的组件,则可以使用withRouter

中的react-router-dom高阶组件
export default withRouter(ComponentThatHasLogoutMethod)

这会将历史记录属性传递给您的组件,并且您不会得到null。

答案 1 :(得分:0)

针对此问题,我们有两种解决方案-:

  • 用粗箭头符号声明替换函数声明,即-:
  logout = () => {
        localStorage.removeItem("token");
        localStorage.clear();
        if(localStorage.getItem('token') === null){
            this.props.history.push('/login');
        }
    }
  • 我们可以在构造函数中绑定logout函数-:
  constructor(props){
      super(props);
      this.logout = this.logout.bind(this);
  }

答案 2 :(得分:0)

在创建自定义门户以显示诸如注销/登录之类的模型时,我遇到了类似的问题。

const App = () => {
  const [modal] = useSelector(({ modal }) => [modal])
  return (
    <>
      <Portal modal={modal} />  
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </>
  );
}

export default App;

正确的方法- 门户网站必须是BrowserRouter的子代。

const App = () => {
      const [modal] = useSelector(({ modal }) => [modal])
      return (
        <>
          <BrowserRouter>
          <Portal modal={modal} />  
            <Routes />
          </BrowserRouter>
        </>
      );
   }

有关Router的更多参考: