[英]React JS component renders multiple times in Meteor
我将 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()
的调用,这可能是因为您在每次渲染时调用该函数。 尝试检查 render 方法之外的值,或者更好的是,依靠测试来确保您的组件正在做它应该做的事情:)
来自https://facebook.github.io/react/docs/component-specs.html#render
render() 函数应该是纯函数,这意味着它不修改组件状态,每次调用时都返回相同的结果,并且不读取或写入 DOM 或以其他方式与浏览器交互(例如,通过使用设置超时)。 如果您需要与浏览器交互,请改为在 componentDidMount() 或其他生命周期方法中执行您的工作。 保持 render() 纯正使服务器渲染更实用,并使组件更易于思考。
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.