У меня есть сценарий, в котором я должен перейти к URL-адресам, например:
localhost: 3000/студенты и localhost:3000/студенты/id
Оба они отображают один и тот же компонент под названием StudentLookup.
Вот мои ссылки и маршруты:
<Link to="/students" />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/students/:id?" component={StudentLookup} />
<Route component={NotFound} />
</Switch>
Теперь в моем StudentLookup я делаю:
class StudentLookup extends Component {
constructor (props) {
super(props)
this.state = { studentId: ''}
this.handleSubmitButton = this.handleSubmitButton.bind(this)
this.onInputChange = this.onInputChange.bind(this)
}
handleSearch (e) {
const { studentId } = this.state
e.preventDefault()
this.props.history.push(`/students/${studentId}`)
this.props.fetchDetailsForStudent(studentId)
}
onInputChange (e) {
this.setState({ studentId: e.target.value })
}
componentDidMount(){
const studentId = this.props.match.params.id
if(id) {
this.setState({studentId})
this.props.fetchDetailsForStudent(studentId)
}
else if(studentId === "") {
this.props.history.push('/');
this.setState({studentId: ''})
}
else
this.setState({ studentId: '' })
}
componentWillReceiveProps(nextProps){
console.log(nextProps.params) // this is always undefined
console.log(this.props.params) // this is always undefined
}
render () {
const studentId = this.props.studentDetails.student_id
return (
<div className="search-container">
<form noValidate="noValidate" onSubmit={this.handleSearch}>
<input type="text" value={this.state.studentId} onChange={this.onInputChange} placeholder="Enter Student Id" />
<button type="Submit">Search</button>
{studentHeader} // we populate this based on id
</form>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
studentDetails: state.studentInfo,
}
}
const mapDispatchToProps = (dispatch, ownProps) => ({
fetchDetailsForStudent (studentId) {
dispatch(fetchDetailsForStudent(studentId))
}
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(StudentLookup))
Когда я нажимаю на localhost: 3000/students, он показывает пустое поле поиска, как и ожидалось, а затем, когда я ввожу идентификатор (в поле поиска или URL-адрес, скажем, 123) и нажимаю ввод, studentInfo заполняется, как и ожидалось (изменение идентификатора в URL-адресе или поиске box также работает) - однако, если я снова нажму на localhost:3000/students, он все равно покажет данные с localhost:3000/students/123. Я ищу способ перезагрузить localhost: 3000/students снова (только с окном поиска и без studentHeader), когда я нажимаю ссылку localhost: 3000/students. Любая помощь приветствуется. Спасибо