【问题标题】:Meteor.userId() not reactive in a react component?Meteor.userId() 在反应组件中没有反应性?
【发布时间】:2019-10-22 04:27:01
【问题描述】:

我刚刚使用 accounts-password 包。身份验证本身工作正常。

在我看来,有些按钮和东西应该只显示给登录的用户。我通过检查Meteor.userId() 得到了这个工作。如果null,按钮将不会显示。

问题如下: 当我登录(或退出)时,我的视图不会重新呈现。它根本不隐藏或显示应切换的按钮。总是需要一个独立的重新渲染来显示或隐藏它们。

Meteor-Documentation 声明,Meteor.userId() 应该是响应式的,但它在我的组件中的行为方式并非如此。

这里有一些 react-component 显示我的视图如何根据Meteor.userId()显示或隐藏按钮:

class SomeReactComponent extends React.Component {
    constructor(props) {
        super(props);
        ...
    }

    ...

    render() {
        return (
            <span>
                <p>Text that should be displayed to anyone!</p>
                { Meteor.userId() ? (
                    <button id="btn">
                        This button is only available to logged in users
                    </button>
                ) : ""}
            </span>
        );
    }
}

【问题讨论】:

    标签: reactjs meteor


    【解决方案1】:

    使用createContainer,这将使您的Meteor.userId() 反应。 安装只需输入:

    meteor npm install --save react-addons-pure-render-mixin

    流星添加反应流星数据

    import React from "react";
    import {createContainer} from "meteor/react-meteor-data";
    
    class SomeReactComponent extends React.Component {
        constructor(props) {
            super(props);
            
        }
    
       
    
        render() {
            return (
                <span>
                    <p>Text that should be displayed to anyone!</p>
                    { this.props.authenticated ? (
                        <button id="btn">
                            This button is only available to logged in users
                        </button>
                    ) : ""}
                </span>
            );
        }
    }
    export default createContainer(()=>{
      return {
        authenticated: Meteor.userId(),
      }
    },SomeReactComponent);
    

    【讨论】:

    • 感谢您的快速建议!我必须这样做的原因是流星反应性不等于反应反应性。所以我必须使用 createContainer() 来包装流星反应性,以便有反应性 ui :) 再次感谢!
    • 是的,通过使用 createContainer 将我们的组件包装到容器中,它将使我们的数据具有反应性。
    【解决方案2】:

    另一个值得研究的答案是 trackerReact 包,位于 https://github.com/ultimatejs/tracker-react

    使用它应该使组件具有反应性,就像您期望的那样。

    class SomeReactComponent extends TrackerReact(React.Component) {
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多