我正在构建styleguide应用程序。我有两个下拉组件,用户可以在其中选择一个品牌和一个组件 - 然后,该应用将根据所选品牌显示所选的组件。我希望这两个选项都包含在URL中。
在编程上更改路线的两个下拉列表。我会收到错误typeerror:每当用户与任何一个下拉列表进行交互时,都无法读取未定义的属性"历史记录"。
我有一个路由渲染的组件:
<Route path="/:brand/:component"
render={props => <DisplayComponent {...props} />} />
该组件有两个用于两个下拉组件的事件处理程序,让用户选择root:
handleComponentPick(event: any) {
const component = event.target.value;
this.props.history.push(`/${this.props.match.params.brand}/${component}`);
}
handleBrandChange = (event: any) => {
if (event.target instanceof HTMLElement) {
const brand = event.target.value;
this.props.history.push(`/${brand}/${this.props.match.params.component}`);
}
};
render = () => {
return (
<div className={"constrain-width-wide center "}>
<ThemePicker
component={this.props.match.params.component}
brand={this.props.match.params.brand}
handleBrandChange={this.handleBrandChange}
handleComponentPick={this.handleComponentPick}
/>
<div className="currently-selected-component" />
<Route path="/:brand/button" component={Button} />
<Route path="/:brand/card" component={Card} />
</div>
);
};
}
我将整个应用程序包装在Router
中。
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);```
如果使用jest
在测试中遇到此错误,则需要将组件包装在路由器中。我正在使用React-Testing-library,因此我的逻辑看起来如下:
import { render, cleanup } from '@testing-library/react'
import { BrowserRouter as Router } from 'react-router-dom'
import YourComponent from '../path/to/YourComponent'
// ...
describe('YourComponent component', () => {
afterEach(cleanup)
it('matches snapshot', () => {
const { asFragment } = render(
// The following will solve this issue
<Router>
<YourComponent />
</Router>
)
expect(asFragment()).toMatchSnapshot()
})
})
您可以尝试以下更改 handleComponentPick(event: any) {
至handleComponentPick = (event: any) => {
然后 render = () => {
至render() {
希望这有效。
您必须像
这样的历史记录 <Router history={browserHistory} routes={routes} />,
这样,您可以将历史记录与道具一起导航。
字体:https://github.com/reacttraining/react-router/blob/v3/docs/guides/guides/histories.md
尝试在app.js上使用浏览史,例如
render(
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route path='features' component={Features} />
</Route>
</Router>,
document.getElementById('app')
)
这样,您正在使用另一个路由器的历史记录。
我们需要将history
作为Prop传递给Router
。我希望您正在使用React Router V4 aka react-router-dom
。
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";
const history = createBrowserHistory();
...
<Router history={history}>
<Routes />
</Router>
演示:https://codesandbox.io/s/yv5y905ojv
在useHistory()
钩上窥视并提供了模拟路由数据。
import routeData from 'react-router';
describe('<Component /> container tests', () => {
beforeEach(() => {
const mockHistory = {
pathname: '/dashboard'
};
jest.spyOn(routeData, 'useHistory').mockReturnValue(mockHistory);
});