so far this is my search component
import React from "react";
import PropTypes from "prop-types";
class Search extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired,
};
searchRef = React.createRef();
handleSubmit = (e) => {
e.preventDefault();
const searchTerm = this.searchRef.current.value;
// get the value of that input
this.context.router.history.push(`/search/${searchTerm}`);
};
render() {
return (
<div className="search">
<form onSubmit={this.handleSubmit}>
<input
type="text"
ref={this.searchRef}
placeholder="Hoppy"
//assign that ref to a DOM node
/>
<input type="submit" value="Search" />
</form>
</div>
);
}
}
export default Search;
我要做的是使用push
方法更新浏览器的URL但是我得到的错误=警告:失败的上下文类型:上下文router
在Search
中标记为必需,但其值为undefined
。我已经搜索了这个错误,大多数人说这是由于特定版本的react-router所致,但是当我使用其他版本时,它没有什么区别,我该如何解决这个问题?有人可以给我举个例子吗?
为了让React Router将其API注入您的组件,您需要将<Search />
组件与react-router的上下文组件一起包装-<Router />
喜欢这个:
import { BrowserRouter as Router } from "react-router-dom";
<Router>
<Search />
</Router>
https://codesandbox.io/s/funny-mirzakhani-pi4v1?file=/src/App.js