我正在构建一个样式指南应用程序。我有两个下拉组件,用户可以在其中选择品牌和组件 - 然后应用程序将根据所选品牌显示所选组件的品牌。我希望这两个选项都包含在 URL 中。
以编程方式更改路线的两个下拉菜单。我收到错误 TypeError: Cannot read property 'history' of undefined 每当用户与任一下拉菜单交互时。
我有一个组件被路由渲染:
<Route path="/:brand/:component"
render={props => <DisplayComponent {...props} />} />
该组件有两个事件处理程序,用于两个下拉组件,让用户选择根:
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()
})
})
关于javascript - React Router - 无法读取未定义的属性 'history',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54982008/