首页 > 解决方案 > reactjs如何在嵌套路由中转到父级路由

问题描述

假设我直接从浏览器访问 URL

http://localhost:3000/developerList/developer/2

我将在页面上有一个返回按钮,该按钮应该返回父路由,以

http://localhost:3000/developerList/

我怎样才能做到这一点?我无法使用

history.goBack()

因为这会触发浏览器返回行为,该行为实际上会返回到 google.com(假设我来自那里)

我也不能用

history.push('/developerList') 

因为那不是动态的。

我知道这是可以做到的,从你可以做 $state.go('^'); 的角度背景开始。它知道删除当前路由 /developer/2 (是的,甚至 /2 部分)。

任何机会都可以通过库做出反应,或者我必须写一些东西。对于我的生活,我无法弄清楚。

这是我的路由结构:

应用程序.js

export class App extends React.Component {
  render() {
    return (
      <Router>
        <Route path='/developerList'>
          <DeveloperListPage></DeveloperListPage>
        </Route>
      </Router>
        );
    }
}

DeveloperListPage.js

export class DeveloperListPage extends React.Component {
  render() {
    return (
      <div className="developer-list-page">
        <Route path='/developerList/developer/:id'>
          <DeveloperPage></DeveloperPage>
        </Route>
      </div>
    )
  }
}

现在在 DeveloperPage 我希望有一个返回功能

标签: reactjsreact-router

解决方案


DeveloperListPage页面/组件级别,您可以使用当前路由匹配来获取匹配的路径以呈现它。创建一个gotoParent回调函数,使用 a history.push“返回”到这个父组件。

示例代码:

应用程序

function App() {
  return (
    <div className="App">
      <Router>
        <ul>
          <li>
            <Link to="/">/home</Link>
          </li>
          <li>
            <Link to="/developerList">/developerList</Link>
          </li>
        </ul>
        <Route path="/developerList">
          <DeveloperListPage />
        </Route>
      </Router>
    </div>
  );
}

开发者列表页面

const DeveloperListPage = () => {
  const history = useHistory();
  const { path } = useRouteMatch(); // get matched path

  const gotoParent = () => history.push(path); // go to this path

  return (
    <div className="developer-list-page">
      <ul>
          <li>
            <Link
              to={`/developerList/developer/${Math.floor(
                Math.random() * 1000
              )}`}
            >
              /developerList/developer/:id
            </Link>
          </li>
        </ul>
      <Route path="/developerList/developer/:id">
        <DeveloperPage gotoParent={gotoParent} /> // <-- pass callback
      </Route>
    </div>
  );
};

开发者页面

const DeveloperPage = ({ gotoParent }) => { // <-- destructure callback
  const history = useHistory();
  const { id } = useParams();
  return (
    <div>
      Developer Page: {id}
      <div>
        <button onClick={gotoParent} type="button"> // <-- attach callback
          Go to parent
        </button>
        <button onClick={history.goBack} type="button">
          Go Back
        </button>
      </div>
    </div>
  );
};

演示

初始网址:"/developerList/developer/174"

  • 尝试“返回”按钮
  • 尝试“转到父级”按钮并查看差异

编辑 reactjs-how-to-go-to-parents-route-in-nested-routings

注意:如果您不想显式地将“gotoParent”回调传递给子路由,您可以轻松地将其抽象到 React 上下文中以提供“最近的”父组件以跳转到。


推荐阅读