Javascript 反应路由器-无法读取属性';历史';未定义的
我正在构建一个styleguide应用程序。我有两个下拉组件,用户可以选择一个品牌和一个组件-然后应用程序将根据所选品牌显示所选组件的品牌。我希望这两个选项都包含在URL中 通过编程更改路线的两个下拉列表。我收到错误TypeError:每当用户与任一下拉列表交互时,无法读取undefined的属性“history” 我有一个由管线渲染的组件:Javascript 反应路由器-无法读取属性';历史';未定义的,javascript,reactjs,typescript,react-router,react-router-v4,Javascript,Reactjs,Typescript,React Router,React Router V4,我正在构建一个styleguide应用程序。我有两个下拉组件,用户可以选择一个品牌和一个组件-然后应用程序将根据所选品牌显示所选组件的品牌。我希望这两个选项都包含在URL中 通过编程更改路线的两个下拉列表。我收到错误TypeError:每当用户与任一下拉列表交互时,无法读取undefined的属性“history” 我有一个由管线渲染的组件: <Route path="/:brand/:component" render={props => <DisplayComponent
<Route path="/:brand/:component"
render={props => <DisplayComponent {...props} />} />
你能试试下面的改变吗
handleComponentPick(event:any){
tohandleComponentPick=(event:any)=>{
然后
render=()=>{
到render(){
希望这行得通。你必须像这样通过历史
<Router history={browserHistory} routes={routes} />,
,
这样,您就可以使用历史和道具来导航
字体:
尝试在app.js上使用browserHistory,如
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')
)
渲染(
,
document.getElementById('app')
)
通过这种方式,您将传递所有其他路由器的历史记录。我们需要传递
历史记录
作为路由器
的道具。我希望您使用的是react router v4 akareact router dom
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";
const history = createBrowserHistory();
...
<Router history={history}>
<Routes />
</Router>
从“历史”导入{createBrowserHistory};
从“react Router dom”导入{Router};
const history=createBrowserHistory();
...
演示:监视
useHistory()
挂钩并提供模拟路线数据
import routeData from 'react-router';
describe('<Component /> container tests', () => {
beforeEach(() => {
const mockHistory = {
pathname: '/dashboard'
};
jest.spyOn(routeData, 'useHistory').mockReturnValue(mockHistory);
});
从“反应路由器”导入路由数据;
描述(‘容器测试’,()=>{
在每个之前(()=>{
常数mockHistory={
路径名:'/dashboard'
};
jest.spyOn(路由数据,'useHistory').mockReturnValue(mockHistory);
});
如果您在使用jest
的测试中遇到此错误,则需要将组件封装在路由器中。我正在使用,因此我的逻辑如下所示:
从'@testing library/react'导入{render,cleanup}
从“react Router dom”导入{BrowserRouter as Router}
从“../path/to/YourComponent”导入您的组件
// ...
描述('YourComponent',()=>{
每次之后(清理)
它('匹配快照',()=>{
const{asFragment}=render(
//下面将解决此问题
)
expect(asFragment()).toMatchSnapshot()
})
})
请检查这指的是什么内部handleComponentPick方法。您可能需要首先在构造函数中绑定它。handleComponentPick似乎没有绑定到类context@ShubhamKhatri,是的,这应该可以解决它。因为它找不到道具本身。
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";
const history = createBrowserHistory();
...
<Router history={history}>
<Routes />
</Router>
import routeData from 'react-router';
describe('<Component /> container tests', () => {
beforeEach(() => {
const mockHistory = {
pathname: '/dashboard'
};
jest.spyOn(routeData, 'useHistory').mockReturnValue(mockHistory);
});