gpt4 book ai didi

hyperlink - 如何调试 React Router?

转载 作者:行者123 更新时间:2023-12-03 13:10:52 27 4
gpt4 key购买 nike

我正在尝试在我的 React 应用程序中使用 React Router,它被限制为 WordPress 插件,并使用 Flux 来获取 api 数据。

我的入口点如下所示

import React from 'react';
import Workshops from './components/workshops';
import Workshop from './components/workshop';
import NotFound from './components/notfound';
import Router, { Route, DefaultRoute, NotFoundRoute, Redirect, Link } from 'react-router';
import json from './config.json';
localStorage.clear();
localStorage.setItem('workshops', JSON.stringify(json));

const AppRoutes = (
<Route path="/" handler={Workshops}>
<DefaultRoute handler={Workshop} />
<Route name="workshop" path=":slug" handler={Workshop}/>
<NotFoundRoute handler={NotFound} />
</Route>
);

Router.run(AppRoutes, Router.HashLocation, (Root) => {
React.render(<Root />, document.getElementById('workshop-booker'));
});

比在我的 Workshops 组件中,我创建了一些指向给定路由的链接,我进行了哈希更改,但路由组件不会被触发。

<h3> <Link to="workshop" params={{slug: workshop.slug }}> {workshop.title.rendered }</Link></h3>

最佳答案

您可以使用 DebugRouter 包装您的路由器,它将打印所做的导航操作:

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Login from 'components/Login'
import DefaultComponent from 'components/DefaultComponent'

class DebugRouter extends BrowserRouter {
constructor(props){
super(props);
console.log('initial history is: ', JSON.stringify(this.history, null,2))
this.history.listen((location, action)=>{
console.log(
`The current URL is ${location.pathname}${location.search}${location.hash}`
)
console.log(`The last navigation action was ${action}`, JSON.stringify(this.history, null,2));
});
}
}

class App extends Component {
render() {
return (
<DebugRouter>
<Switch>
<Route exact path="/login" name="Login Page" component={Login} />
<Route path="/" name="Home" component={DefaultComponent} />
</Switch>
</DebugRouter>
);
}
}

link to the gist

关于hyperlink - 如何调试 React Router?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34093913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com