在meteorJS应用程序的主要组件<App />中,我使用了一些用户数据(const user = Meteor.user())。如果user-object具有check值,则将使用<AnotherComponent />。在那里,用户可以进行一些交互,并且从user文档中删除check字段。
说得更清楚一点:通过更新db中的值,check值将在另一个位置被删除。
现在我期望,现在将呈现<MainComponent />。但它不会。我需要重新加载页面才能获得它。
有没有办法让user变量变得“反应性”?
class App extends Component {
render () {
const user = Meteor.user()
if (user && user.check) {
return (<AnotherComponent />)
}
return (<MainComponent />)
}
}发布于 2017-08-11 05:14:03
尝试将用户声明移动到状态。这样,当Meteor.user()更新时,它将更新状态并触发重新呈现。
class App extends Component {
constructor(){
super();
this.state = {
user: Meteor.user()
}
}
render () {
const { user } = this.state;
if (user && user.check) {
return (<AnotherComponent />)
}
return (<MainComponent />)
}
}发布于 2017-08-11 05:19:19
如果要重新加载渲染器,组件需要一个状态可以更改变量。或者接受一些新的道具。
在您的情况下,这是正常的,您必须重新加载页面。
如果您想在应用程序组件中运行render(),则需要将用户存储在一个状态中,并找到一种方法再次调用Meteor.user来检索一些新数据并替换为用户状态。如果state.user已更改,则您的组件将重新呈现。
class App extends Component {
constructor() {
super();
this.state = {
user: Meteor.user(),
}
this.smthChanging = this.smthChanging.bind(this);
}
smthChanging() {
this.setState({
user: Meteor.user(),
});
}
render () {
const { user } = this.state;
if (user && user.check) {
return (<AnotherComponent />)
}
return (
<div>
<button
onClick={this.smthChanging}
>
reload user
</button>
</div>
)
}
}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
https://stackoverflow.com/questions/45622833
复制相似问题