admin管理员组文章数量:1405730
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 badges1 Answer
Reset to default 4A 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.
本文标签: javascriptHow to make component rerender when value from outside changesStack Overflow
版权声明:本文标题:javascript - How to make component re-render when value from outside changes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744919221a2632188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论