javascript - React JS 组件在 Meteor 中渲染多次

标签 javascript meteor reactjs es5-shim

我在这个应用程序中使用 Meteor 1.3 以及 React js 和 Tracker React。 我有一个页面可以查看应用程序中的所有可用用户。该页面需要用户登录才能查看数据。如果用户未登录,它将显示登录表单,登录后组件将呈现用户的数据。

逻辑的主要组件。

export default class MainLayout extends TrackerReact(React.Component) {
    
    isLogin() {
        return Meteor.userId() ? true : false
    }
    render() {
    
        if(!this.isLogin()){
            return (<Login />)
        }else{
        return (
            <div className="container">
                <AllUserdata  />            
            </div>
          )
        }
    }
}

AllUserdata组件中:

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

    constructor() {
        super();

        this.state ={
            subscription: {
                Allusers : Meteor.subscribe("AllUsers")
            }
        }

    }

    componentWillUnmount(){
        this.state.subscription.Allusers.stop();
    }

    allusers() {
        return Meteor.users.find().fetch();
    }

    render() {
        console.log('User objects ' + this.allusers());
        return (
                <div className="row">
                    {
                    this.allusers().map( (user, index)=> {
                            return <UserSinlge key={user._id} user={user} index={index + 1}/>
                            })
                     }

                        
                </div>
                
            )
    }   
};

问题是登录时,它只显示当前用户的数据。所有其他用户对象都不会呈现。如果我在控制台上检查, console.log('User objects ' + this.allusers()); 显示对象被渲染 3 次:第一次渲染仅显示当前用户的数据,第二次渲染渲染所有用户的数据(期望的结果),第三个再次仅渲染当前用户的数据。

如果刷新页面,用户数据将正确呈现。

知道为什么吗?

最佳答案

React 在运行时会多次调用组件的 render() 方法。如果您遇到意外调用,通常是某些东西触发了组件的更改并启动了重新渲染。看起来有些东西可能会覆盖对 Meteor.users.find().fetch() 的调用,这可能是因为您在每个渲染上调用该函数而发生的。尝试检查渲染方法外部的值,或者更好的是,依靠测试来确保您的组件正在执行应有的操作:)

来自https://facebook.github.io/react/docs/component-specs.html#render

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout). If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes server rendering more practical and makes components easier to think about.

另请参阅:

关于javascript - React JS 组件在 Meteor 中渲染多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752862/

相关文章:

javascript - 使用 Clip() 重复纹理以循环

Javascript 生成的日历在 mozilla firefox 和 chrome 中显示不同

javascript - 管理员登录后如何访问网站的其他页面

reactjs - 您应该将应用程序状态存储在本地状态还是 Redux Store 中

reactjs - 如何在 React Native Flexbox 中水平包装项目?

javascript - Angular2未捕获引用错误: Class is not defined

javascript - Jquery 更改鼠标悬停值

javascript - 如何在 meteor 中生成生成的 html 页面的语义 URL?

javascript - Meteor 1.8.1 SSL 双连接

javascript - 在 React/Flux 应用程序中,延迟操作超时属于哪里?