繁体   English   中英

ReactJS:如果变量值改变,则重新加载组件

[英]ReactJS: Reload component if variable changes value

在我的meteorJS应用程序的主要组件<App /> ,我正在使用一些用户数据( const user = Meteor.user() )。 如果user <AnotherComponent />具有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 />)
  }
}

尝试将用户声明移动到状态。 这样,当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 />)
  }
}

如果要重新加载渲染,则组件需要一个可以更改状态的变量。 或者收到一些新的道具。

在您的情况下,这是正常的,您需要重新加载页面。

如果要在App组件中运行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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM