我正在编写一个用于搜索elasticsearch实例的简单搜索组件。我已经设置了所有的redux,所以我的搜索查询存储在redux中,并且当用户位于/ search页面上时,将呈现结果。可从导航栏(在任何页面上)访问我的搜索栏,并且当用户按下Enter键时,我试图重定向到结果页面(“ /搜索”)。我正在App.js中使用顶级组件。
我尝试使用and history.push(“ / search”),但更改了URL,并且网页未呈现新页面。
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import { connect } from "react-redux";
import elasticsearchUtility from "../utilities/elastic-search-utility";
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
flexDirection: 'row',
},
margin: {
margin: theme.spacing.unit,
},
cssLabel: {
color: 'white',
'&$cssFocused': {
color: 'white',
},
},
cssFocused: {
},
cssUnderline: {
color: 'white',
},
cssOutlinedInput: {
'&$cssFocused $notchedOutline': {
borderColor: 'white',
},
},
notchedOutline: {
borderWidth: '1px',
borderColor: 'white !important'
},
});
class Search extends Component{
state = {
searchQuery: ""
};
onChange = event => {
this.props.updateQuery(event.target.value);
};
render() {
const {searchQuery, classes} = this.props;
return (
<div className={this.props.classes.container}>
<TextField
fullWidth={true}
className={classes.margin}
InputLabelProps={{
classes: {
root: classes.cssLabel,
focused: classes.cssFocused,
},
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline,
},
}}
onChange={this.onChange}
label="Service search"
variant="outlined"
id="custom-css-outlined-input"
value={searchQuery}
/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
query: state.searchQuery
}
};
const mapDispatchToProps = (dispatch) => {
return {
updateQuery: (query) => {
dispatch(search(query))
}
}
};
function search(value) {
return {type: "SEARCH", value};
}
Search.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(Search)
);
我希望当用户按下Enter键(启动搜索)时页面会呈现我的搜索结果,实际上/ search被推送到URL,但是页面并未呈现。
答案 0 :(得分:0)
import { withRouter } from 'react-router-dom';
onChange = event => {
this.props.updateQuery(event.target.value);
this.props.history.replace('/search');
};
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(withRouter)(Search)
);
您需要使用withRouter包装组件并像这样使用。
答案 1 :(得分:0)
答案:默认情况下,需要将connect
包装在withRouter
中,并使用this.props.history.push(“ / search”)。
export default withStyles(styles)(withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(Search))
);