2017-04-22 44 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通话,但它可能取决于你的使用情况。