在React中导航到新页面时,如何强制卸载组件?

时间:2018-08-29 00:02:27

标签: reactjs react-router react-dom

我有一个主页,其中包含指向表单的链接,如下所示:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
  NavLink,
  Redirect,
  Switch,
  withRouter
} from "react-router-dom"; 
import addHand from './Forms/addHand'

export class Home extends Component { 

  render() { 
      return ( 
        <div> 
          <Router> 
          <div>
          <NavLink to= '/hands/new'> Add a new hand </NavLink> 
          <Route path= '/hands/new' component={addHand}/> 
          <h4> Search For Hands By Category </h4> 
          <h4> Search For Sessions By Category </h4> 
          <h4> Search For Tables By Category </h4> 
          </div> 
          </Router>
        </div> 
      ); 
  }
} 

export default Home; 

我也有一个导航栏,该导航栏带有一个链接,可以从任何页面返回首页,如下所示:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';  
import unmountComponentAtNode from 'react-dom';

class NavBar extends Component { 

  render() {
    return (
      <div className="navbar"> 
        <NavLink className="link"
        to="/"
        exact 
      >Home</NavLink> 
      </div>
    ); 
  }
};

export default NavBar; 

如果我转到表单,然后改变主意并决定要返回主页,那么当我按下navlink时,URL会更改,但是表单仍会显示在主页上。我可以在路由之间来回移动,但是要从DOM中卸载表格的唯一方法是刷新页面。是什么导致了这种现象,我该怎么做才能解决?我之前在React中遇到过类似的问题,但从未找到解决方案。谢谢!

编辑**我尝试将其添加到导航链接:

render() {

const refCallback = node => {
  unmountComponentAtNode(node)
}

return (
  <div className="navbar"> 
    <NavLink className="link"
    to="/"
    exact 
    innerRef={refCallback}
  >Home</NavLink> 
  </div>
); 
}
}; 

根据React Router文档,但是它给了我这个错误:

unmountComponentAtNode(...):目标容器不是DOM元素。

这是app.js中的代码

import React, { Component } from 'react';
import './App.css'; 
import { Router, Route } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import Home from './Components/Home'
import Navbar from './Components/Navbar';
import addHand from './Components/Forms/addHand';

export const history = createBrowserHistory();

class App extends Component {
  render() {
    return (
     <div className="App">
        <header className="App-header">
          <h1 className="App-title-top">Hi Adam, welcome to your Personal 
Poker Universe!</h1> 
          <h1 className="App-title-middle">Not Adam? GTFO!</h1> 
          <h1 className="App-title-bottom">Just Kidding, you can stay</h1>
        </header> 
        <Router history= {history}> 
          <div>
        <Navbar/> 
        <Route exact path='/' component= {Home} />   
        </div>
        </Router>
      </div>
    );
  }
}

export default App; 

1 个答案:

答案 0 :(得分:0)

在App.js中定义一个Router

<Router history={history}>
  <Switch>
    <Route exact path="/" component={Home} />} />
    <Route  path="/hands/new" component={addHand} />
    </Switch>
</Router>

然后尝试在应该起作用的路线之间导航。请让我知道它是否无效