我有一个情景,我可以导航到以下网址:
localhost:3000 /学生和localhost:3000 / students / 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 /学生时,它会按预期显示空的搜索框 - 然后当我输入一个id(在搜索框中或url说123)并按Enter键时,studentInfo按预期填充(更改id中的网址或搜索框也有效) - 但是,如果我再次点击localhost:3000 /学生,它仍会显示来自localhost:3000 / students / 123的数据。 我正在寻找一种方法来重新加载localhost:3000 /学生(只有搜索框而没有studentHeader)当我点击localhost:3000 / students链接时。 任何帮助表示赞赏。感谢
答案 0 :(得分:0)
使用componentWillUpdate或componentWillRecieveProps或componentDidUpdate检查路径中是否存在特定参数。如果不存在,请将处于该状态的studentId设置为空。
代码将是这样的。
componentWillReceiveProps(nextProps)
{
if(!nextProps.match.params.id)
this.setState({studentId : ''})
}