简体   繁体   English

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

[英]ReactJS: Reload component if variable changes value

In my main component <App /> of my meteorJS application I'm using some user data ( const user = Meteor.user() ). 在我的meteorJS应用程序的主要组件<App /> ,我正在使用一些用户数据( const user = Meteor.user() )。 If the user -object has a check value <AnotherComponent /> will be used. 如果user <AnotherComponent />具有check值,则将使用<AnotherComponent /> There the user can do some interaction and the check field gets removed from user document. 用户可以在那里进行一些交互,并从user文档中删除check字段。

To make it a bit clearer: The check value will be removed on another place by updating the value in the db. 为了使它更清楚:通过更新db中的值,将在另一个地方删除check值。

Now I would expect, that now <MainComponent /> will be rendered. 现在我希望,现在将呈现<MainComponent /> But it won't. 但事实并非如此。 I need to reload the page to get it. 我需要重新加载页面才能获得它。

Is there a way how I can make the user variable 'reactive'? 有没有办法让我的user变量'反应'?

class App extends Component {
  render () {
    const user = Meteor.user()

    if (user && user.check) {
      return (<AnotherComponent />)
    }
    return (<MainComponent />)
  }
}

Try moving the user declaration into state. 尝试将用户声明移动到状态。 That way, when Meteor.user() updates, it will update state and trigger a re-render. 这样,当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 />)
  }
}

if you want to reload a render, your component has need a variable in a state that can be change. 如果要重新加载渲染,则组件需要一个可以更改状态的变量。 Or receive some new props. 或者收到一些新的道具。

In your case, this is normal you've to reload the page. 在您的情况下,这是正常的,您需要重新加载页面。

if you want to run render() in App component, you need to store the user in a state, and find a way to call Meteor.user again to retrieve some new data and replace in the user state. 如果要在App组件中运行render(),则需要将用户存储在某个状态,并找到再次调用Meteor.user的方法来检索一些新数据并替换为用户状态。 If the state.user has changed, then, your component will be rerendering. 如果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