如標題所說的問題,更詳細一點就是多個router使用同一個react頁面組件的時候,當切換路由的時候,頁面組件不重新構建,頁面也不刷新。
例如:
router.js
import Index from './routes/Index/index';
import UserAccount from './routes/UserAccount/index';
const Root = () =>(
<Router history={history} >
<div style={{ height:'100%' }}>
<Route exact path='/' component={Login} />
<Route path="/sem" component={Layout}>
<Route path="Index" component={Index} />
<Route path="UserAccount" component={UserAccount} />
<Route path="UserAccountForMaster" component={UserAccount} />
<Route path="UserAccountForNormal" component={UserAccount} />
</Route>
</div>
</Router>
)
ReactDOM.render(<Root />,document.getElementById('root'))
UserAccount.js
import React from 'react';
export default class UserAccount extends React.Component {
constructor (props) {
super(props);
this.state = {
dataList:[]
}
}
componentWillMount () {
}
componentDidMount () {
sendFetch('http://www.baidu.com', {type:1}, 'GET')
.then(data=>{
this.setState({ listData:data.data.lists })
})
}
render () {
return (
<div>
<button>你好,祝你幸福,再見~</button>
<ul>
{
listData.length !== 0 ? listData.map((item,index)=>{
return <li>{item.name}</li>
}) : null
}
</ul>
</div>
)
}
}
以上情況當路由切換的時候,組件UserAccount
只是重新render,並不重新構建,如果需要路由切換的時候,組件重新構建,重新完成一次生命週期,則需要給組件加上key
;方法如下:
·····這是解決辦法·····這是解決辦法·····這是解決辦法·····這是解決辦法·····這是解決辦法·····這是解決辦法·····
路由不需要修改,我們只需要修改組件:
上面提到需要給組件加上key,讓router
的path
屬性(params)指向組件的key,就可以實現,組件的重構。
UserAccount.js
import React from 'react';
// 注意這裏
class UserAccount extends React.Component {
constructor (props) {
super(props);
this.state = {
dataList:[]
}
}
componentWillMount () {
}
componentDidMount () {
sendFetch('http://www.baidu.com', {type:1}, 'GET')
.then(data=>{
this.setState({ listData:data.data.lists })
})
}
render () {
return (
<div>
<button>你好,祝你幸福,再見~</button>
<ul>
{
listData.length !== 0 ? listData.map((item,index)=>{
return <li>{item.name}</li>
}) : null
}
</ul>
</div>
)
}
}
// 注意這裏
export default (props)=><UserAccount {...props} key={props.location.pathname} />
這裏的props.location.pathname
就是router的path屬性的值,這樣就實現了,router的path屬性指向組件的key。
這樣切換路由的時候,即可完成組件的刷新(重構)。