【问题标题】:React D3 component did not get unmounted upon (component) redirect using history.push()React D3 组件在使用 history.push() 重定向(组件)时没有被卸载
【发布时间】:2019-01-06 22:58:26
【问题描述】:

React D3 组件在使用以下方法重定向(组件)时未卸载。也就是说,在 SPA 中,在“graphA”上,单击按钮会重定向到“graphB”。 'graphB' 被渲染,但是,'graphA' 仍然可见。关于如何删除/卸载“graphA”以便只有“graphB”可见的想法。我尝试在各种 React 生命周期挂钩中调用 ReactDOM.unmountComponentAtNode(),但均未成功。

this.props.history.push({ pathname: '/graphB' })

【问题讨论】:

  • 您是否尝试过使用<Switch> 组件?
  • 你用的是什么路由器?如果您确实使用了来自 react-router 的 像 @Colin 提到的,除非您的匹配模式错误,否则不会发生这种情况。
  • 公平地说,您的问题中缺少大量信息,这几乎无法提供帮助。

标签: javascript reactjs d3.js


【解决方案1】:

假设您使用的是 React Router,这就是使用 Switch 组件的方法。它将为匹配的第一个路径渲染组件。

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

const A = () => <h1>A</h1>
const B = () => <h1>B</h1>

const Landing = ({ history }) => {
  const goToA = () => {
    history.push('a');
  }

  const goToB = () => {
    history.push('b');
  }

  return (
    <div>
      <button onClick={goToA}>Go to A</button>
      <button onClick={goToB}>Go to B</button>
    </div>
  )
}

const App = ({ history }) => {
  return (
    <Switch>
      <Route exact path="/" component={Landing} />
      <Route path="/a" component={A} />
      <Route path="/a" component={A} />
    </Switch>
  )
}
render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
  , document.getElementById('root'));

现场示例here

【讨论】:

  • 抱歉,我更改了网址。立即尝试链接。
猜你喜欢
  • 2021-07-10
  • 2020-04-27
  • 2019-08-03
  • 1970-01-01
  • 2020-09-28
  • 2020-10-07
  • 2017-08-23
  • 2017-11-06
  • 2021-04-26
相关资源
最近更新 更多