这是一个新闻api,但我不知道如何让搜索引擎工作,也就是说,我想这样做this.props.history.push("/:query")
但它不工作,这是我的jsx代码。
路线
<BrowserRouter>
<Container maxWidth="lg">
<Header />
<Nav />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/categorias/:category" exact component={Category} />
<Route path="/busqueda/:query" component={Busqueda} />
</Switch>
</Container>
</BrowserRouter>
这是搜索组件
class Busqueda extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = event => {
this.setState({ data: event.target.value });
this.props.history.push("/:query");
};
render() {
return (
<Fragment>
<div className="container">
<form className="text">
<input
className="text__input"
type="text"
placeholder="Ingresa un texto"
onChange={this.handleChange}
/>
<button className="text__button">buscar</button>
</form>
</div>
</Fragment>
);
}
}
这是我通过搜索组件的地方
class Header extends Component {
render() {
return (
<AppBar position="static">
<StyledToolbar style={{ backgroundColor: "#f50057" }}>
<Typography variant="h6">News Feeds</Typography>
<Busqueda />
</StyledToolbar>
</AppBar>
);
}
}
它给了我一个错误,说 push 方法this.props.history.push("/:query")
是未定义的。
尝试
Busqueda
使用方法导出组件withRouter
,这会将方法添加history()
到this.props
您的组件中:搜索.jsx: