最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论