【问题标题】:Component mounts before previous component unmounts ( and keeps the subscription )组件在前一个组件卸载之前挂载(并保留订阅)
【发布时间】:2016-11-04 06:28:47
【问题描述】:

我有两个共享布局的基本组件。第一个是条目列表。当用户点击“编辑”时,他会被带到详细信息页面。

问题是详细信息页面显示的是“列表”页面中的第一条记录,而不是用户单击的记录。

我做了一些测试,看起来问题是在 ComponentWIllUnmount() 运行之前加载和安装了详细信息页面,因此来自前一页面的订阅在几毫秒内仍然处于活动状态。如果我直接访问详细信息页面或重新加载它,它会正常工作,因为它没有从上一页获取任何数据。

这是我的代码:

List.jsx

export default class List extends TrackerReact( React.Component ) {

    constructor( props ) {

        super( props );

        var subscription = this.getSubscription();

        this.state = {

            ready: subscription.ready(),
            subscription: subscription,

        }

    }

    componentWillUnmount() {

        this.state.subscription.stop();

    }

    render() {
        return(
        //stuff...
        )
    }

}

Detail.jsx

export default class SkinDetail extends TrackerReact( React.Component ) {

    constructor( props ) {

        super( props );

        const subscription = Meteor.subscribe( 'skins.one', this.props.skin );

        var record = Records.findOne();

        if( record ) {

            this.state = {

                subscription: subscription,
                // Stuff...

            }

        }

    }

    getRecord() {

        return Records.findOne();

    }

    render() {

        var record = this.getRecord(); 

        return(
            // Do stuff with record...
        )

    }
}

我正在为链接和路由使用 FlowRouter SSR。

【问题讨论】:

  • 不要指望记录是唯一可用的。通过_id 找到它。停止订阅需要一些时间(服务器需要让客户端知道要删除的内容等)。

标签: reactjs meteor flow-router


【解决方案1】:

你应该明确找到你的记录,不要依赖从服务器发送的数据。

例如,如果需求发生变化并且您需要在详细信息页面上添加另一个组件以显示另一条记录,则仅使用 Records.findOne 不会为您提供所需的记录。

相反,您应该提供一个查询,例如_id,到.find 以获取记录。您可以使用FlowRouter 定义您的路线以存储_id 值:FlowRouter.route('/details/:_id, {...})

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2018-10-30
    • 2018-04-11
    相关资源
    最近更新 更多