我为此应用程序使用了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读取或写入DOM或以其他方式与浏览器进行交互(例如,通过使用setTimeout)。如果需要与浏览器进行交互,请改为使用componentDidMount()或其他生命周期方法执行工作。保持render()为纯净值可以使服务器渲染更加实用,并使组件更易于考虑。
也可以看看:
https://facebook.github.io/react/docs/advanced-performance.html
https://facebook.github.io/react/docs/top-level-api.html#reactdom
https://ifelse.io/2016/04/04/testing-react-components-with-enzyme-and-mocha/
关于javascript - React JS组件在Meteor中多次渲染,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36752862/