2017-04-22 49 views
0

我有了用戶配置文件的應用程序。在用戶檔案中有一個朋友列表,當點擊一個朋友時,它應該帶你到另一個用戶檔案。更新路線和Redux的狀態數據在同一時間

目前,當我點擊瀏覽其他配置文件(通過終極版路由器鏈接),它更新了網址,但不更新配置文件或呈現新的路線。

下面是一個簡單的代碼片段,我已經採取了很多的代碼爲簡單起見。下面還有一些圖層,但問題發生在我的配置文件容器中的頂層。如果我可以得到userId道具來更新ProfileSections,那麼一切都會傳播。

class Profile extends Component { 

    componentWillMount() { 
    const { userId } = this.props.params 

    if (userId) { this.props.getUser(userId) } 
    } 

    render() { 
    return <ProfileSections userId={user.id} /> 
    } 
} 

const mapStateToProps = ({ user }) => { 
    return { user } 
} 

export default connect(mapStateToProps, { getUser })(Profile); 

正如你所看到的,什麼情況是,我運行的是getUser行動componentWillMount,這隻會發生一次,是路線的變化,但配置文件數據不更新的原因。

當我將其更改爲另一個生命週期鉤,如componentWillUpdate來運行getUser操作時,我進入了一個無限循環的請求,因爲它將不斷更新狀態並更新組件。

我也嘗試過在Route組件上使用react-router提供的onEnter掛鉤,但是從一個配置文件導航到另一個配置文件時它不會觸發,因爲它是相同的路由,所以不起作用。

我相信我想着這以錯誤的方式,我期待獲得一些指導我如何可以處理,而數據存儲在了Redux商店導航從一個配置文件到其他的這種情況。

+0

你可以看看https://github.com/reactjs/react-router-redux它是否適合你的使用情況 – Aprillion

回答

0

所以我建議您通過以下方式處理這個:

class Profile extends Component { 
    componentWillMount() { 
    const { userId } = this.props.params 

    if (userId) { 
     // This is the initial fetch for your first user. 
     this.fetchUserData(userId) 
    } 
    } 

    componentWillReceiveProps(nextProps) { 
    const { userId } = this.props.params 
    const { userId: nextUserId } = nextProps.params 

    if (nextUserId && nextUserId !== userId) { 
     // This will refetch if the user ID changes. 
     this.fetchUserData(nextUserId) 
    } 
    } 

    fetchUserData(userId) { 
    this.props.getUser(userId) 
    } 

    render() { 
    const { user } = this.props 

    return <ProfileSections userId={user.id} /> 
    } 
} 

const mapStateToProps = ({ user }) => { 
    return { user } 
} 

export default connect(mapStateToProps, { getUser })(Profile); 

請注意,我有它的生命週期componentWillMount方法建立這樣,你讓初始userId請求。在componentWillReceiveProps方法的代碼檢查,看是否有新的用戶ID已經收到,(當你瀏覽到一個不同的配置文件,這將發生),如果是的話重新讀取數據。

您可以考慮使用componentDidMountcomponentDidUpdate代替componentWillMountcomponentWillReceiveProps分別爲fetchUserData通話,但它可能取決於你的使用情況。