在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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

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

回答
編輯回答
久礙你

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

componentWillReceiveProps(nextProps) {
    console.log(nextProps, this.props);
    
    // 可以通過nextProp獲取改變后的props,也可以通過this.props獲取當(dāng)前的props
    // 此處處理重繪邏輯(通過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(){
        //這個就是你的stroe,mapStateToProps中做了映射,大致意思就是,只要你觸發(fā)了此類reducer的狀態(tài)變化,那么這個狀態(tài)就會改變,所以這里的狀態(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