0%

React中router-dom相同路径不同参数时页面不重载问题

React中router-dom相同路径不同参数时页面不重载问题。

版本如下:

1
2
3
4
5
6
7
"dependencies": {
"axios": "^0.18.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router-dom": "^5.0.0",
...
},

App.js代码片段:
1
2
3
4
5
6
7
8
9
10
...
<Route path="/lesson/:id" exact render={props=>
<Lesson
base_url={URL}
isLogin={this.state.isLogin}
token={this.state.token}
username={this.state.username}
/>
}/>
...

Lesson.js代码片段:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
...
componentDidMount() {
let id = this.props.match.params.id;
axios({
url: '/app1/lesson/' + id + '/',
headers: {}
})
.then(更新状态)
...
}
...
render(){
return
...
<Row>
<Col>
{lesson.prev_id>0?
<Button
variant="outline-info"
onClick={()=>this.props.history.push('/lesson/'+lesson.prev_id)}
>
上一课:{lesson.prev_title}
</Button>
:<div/>}
</Col>
<Col
className="col-center"
>
<Button
variant="outline-info"
onClick={()=>this.props.history.push('/course/'+lesson.course_id)}
>返回课程列表</Button></Col>
<Col className="col-right">
<Button
variant="outline-info"
onClick={()=>this.props.history.push('/lesson/'+lesson.next_id)}>
下一课:{lesson.next_title}
</Button>
</Col>
</Row>
...
}

现在的问题是,Lesson页面加载后,单击“上一课”、“下一课”,浏览器地址栏改变,页面不重载,显示仍然是初次载入后的数据。

经查这个
)页面:


Along with componentDidMount, You also need to implement the componentWillReceiveProps or use getDerivedStateFromProps(from v16.3.0 onwards) in Products page since the same component is re-rendered with updated params and not re-mounted when you change the route params, this is because params are passed as props to the component and on props change, React components re-render and not re-mounted.

意思是页面加载后,参数是作为属性props传入的,属性的改变并不会导致页面部件更新,状态state的改变才会。

于是将axios获取数据放入单独函数fetchLesson中,增加componentWillReceiveProps函数:

1
2
3
4
5
6
7
componentWillReceiveProps(newProps) {
let id = newProps.match.params.id;
if (typeof(id) !== 'undefined' && id !== null && id !== this.props.match.params.id) {
console.log('will fetch new lesson...')
this.fetchLesson(id);
}
}

componentDidMount修改如下:

1
2
3
4
componentDidMount() {
let id = this.props.match.params.id;
this.fetchLesson(id);
}

问题解决。