export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’

作者: tww844475003 分类: 前端开发 发布时间: 2022-03-01 23:22
import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';

export default () => {
  <div>
    <Switch>
      <Route exact path="/" component={Home}></Route>
      <Route exact path="/about" component={About}></Route>
    </Switch>
  </div>
}

react-router-domV5 升级到 V6 后,有些使用做了一些改变:

  • Switch 重命名为 Routes
// V5
<Switch>
  <Route exact path="/" component={Home}></Route>
  <Route exact path="/post" component={Post}></Route>
</Switch>
// V6
<Routes>
  <Route exact path="/" component={Home}></Route>
  <Route exact path="/post" component={Post}></Route>
</Routes>
  • Route 的新特性变更 ,component/render 被 element 替代
// V5
<Switch>
  <Route exact path="/" component={Home}></Route>
  <Route exact path="/post" component={Post}></Route>
</Switch>
// V6
<Routes>
  <Route exact path="/" element={Home}></Route>
  <Route exact path="/post" element={Post}></Route>
</Routes>
  • useNavigate代替useHistory
// V5
import { useHistory } from 'react-router-dom';

function exitButton() {
  const history = useHistory();
  function handleClick() {
    history.push('/exitLogin');
  };
  return <button onClick={handleClick}>Exit</button>
}

// V6
import { useNavigate } from 'react-router-dom';

function exitButton() {
  const navigate = useHistory();
  function handleClick() {
    navigate('/exitLogin')
  };
  return <button onClick={handleClick}>Exit</button>
}

前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注