javascript - How to make component re-render when value from outside changes? - Stack Overflow

So, I have simple code (class) like this:export default class LoginAction {isLoggedIn = () => {retur

So, I have simple code (class) like this:

export default class LoginAction {
  isLoggedIn = () => {
    return true
  }
}

And I used it in my other classes like this:

export default class Main extends Component {
  render = () => {
    const loginAction = new LoginAction()

    if (loginAction.isLoggedIn()) {
      return (
        <View style={{ flex: 1 }}>
          <Header headerText={'Post List'} />
          <PostList />
        </View>
      )
    }

    ....... (split)
  }
}

The question is, when I change the return value on the isLoggedIn function, why Main ponent not re-rendered?

It's React Native, and I use Hot Reloading.

So, I have simple code (class) like this:

export default class LoginAction {
  isLoggedIn = () => {
    return true
  }
}

And I used it in my other classes like this:

export default class Main extends Component {
  render = () => {
    const loginAction = new LoginAction()

    if (loginAction.isLoggedIn()) {
      return (
        <View style={{ flex: 1 }}>
          <Header headerText={'Post List'} />
          <PostList />
        </View>
      )
    }

    ....... (split)
  }
}

The question is, when I change the return value on the isLoggedIn function, why Main ponent not re-rendered?

It's React Native, and I use Hot Reloading.

Share Improve this question edited Dec 21, 2016 at 9:09 GG. 21.9k14 gold badges92 silver badges133 bronze badges asked Dec 21, 2016 at 8:14 nmfzonenmfzone 2,9231 gold badge23 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

A ponent re-renders only in 2 situations:

  • if its state has changed
  • if the received props have changed

In your Main ponent, none of these situations happen.

To fix it, you could pass isLoggedIn to your ponent:

// index.js

const loginAction = new LoginAction()
let isLoggedIn = loginAction.isLoggedIn()

const setLoggedUser = user => {
  loginAction.setLoggedUser(user)
  isLoggedIn = true
}

ReactDOM.render(
  <div>
    {!isLoggedIn && <Login setLoggedUser={setLoggedUser} />}
    <Main isLoggedIn={isLoggedIn} />
  </div>,
  document.getElementById('root')
)

And use this prop in your ponent's render:

export default class Main extends Component {
  render = () => {
    if (this.props.isLoggedIn) {
      return (
        <View style={{ flex: 1 }}>
          <Header headerText={'Post List'} />
          <PostList />
        </View>
      )
    }
    ...
  }
}

In doing so, your ponent will re-render when isLoggedIn changes.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744919221a4601028.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信