鍍金池/ 問(wèn)答/HTML5  HTML/ React router 4 帶參數(shù)的路由,從"/album?id=1

React router 4 帶參數(shù)的路由,從"/album?id=1"訪問(wèn)"/album?id=2"該如何重新渲染?

<HashRouter>
        <main>
          <Switch>
            <Route exact path="/" component={IndexPage} />
            <Route path="/login" component={Login} />
            <Route path="/album" component={Album} />
          </Switch>
        </main>
      </HashRouter>

如題,定義了一個(gè)名為album的route,
然后在此路由的component的componentDidMount里,
獲取到this.props.location.search,即"?id=1",通過(guò)異步獲取數(shù)據(jù)然后更新store,觸發(fā)此組件的re-render,
這個(gè)組件里面有個(gè)鏈接為"/album?id=2"的Link,由于只改變了查詢字段,沒(méi)有觸及pathname的更新,所以此鏈接能點(diǎn),history也會(huì)更新,componentDidUpdate也能看到props.location.search改變,但是store并不更新,所以組件也不會(huì)re-render...
所以我該在什么地方更新store呢?

回答
編輯回答
久礙你

可以使用componentWillReceiveProps重新渲染,這個(gè)鉤子函數(shù)會(huì)在組件傳入的 props 發(fā)生變化時(shí)調(diào)用。

componentWillReceiveProps(nextProps) {
    console.log(nextProps, this.props);
    
    // 可以通過(guò)nextProp獲取改變后的props,也可以通過(guò)this.props獲取當(dāng)前的props
    // 此處處理重繪邏輯(通過(guò)setState觸發(fā)視圖渲染)...
  }
2017年8月13日 05:37
編輯回答
爆扎

首先你的/album路由需要改造一下:

//:id 為你的id參數(shù)占位標(biāo)記
<Route path="/album/:id" component={Album} />

在Album中

class Album extends Component {
    componentDidMount() {
        //這里獲取你每次url中id位的值
        let id = this.props.match.params.id;
        //依據(jù)id參數(shù)變化 觸發(fā)你的業(yè)務(wù)
        //如:這里使用redux
        this.props.action.getAlbum(id)
    }
    render(){
        //這個(gè)就是你的stroe,mapStateToProps中做了映射,大致意思就是,只要你觸發(fā)了此類reducer的狀態(tài)變化,那么這個(gè)狀態(tài)就會(huì)改變,所以這里的狀態(tài)永遠(yuǎn)都是最新的,也正是你想要的.
        console.log(this.props.album);
        return(
            ...
        )
    }
}
const mapStateToProps = (state) => {
    return {
        album: state.album,
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        action: bindActionCreators(albumActions, dispatch)
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(Album);
2017年3月14日 04:33