I'm stating to learn react and redux today, yet I cannot figure out how to force component to rerender after state change.
Here is my code:
const store = createStore(loginReducer);
export function logout() { return {type: 'USER_LOGIN'} }
export function logout() { return {type: 'USER_LOGOUT'} }
export function loginReducer(state={isLogged:false}, action) {
switch(action.type) {
case 'USER_LOGIN':
return {isLogged:true};
case 'USER_LOGOUT':
return {isLogged:false};
default:
return state;
}
}
class App extends Component {
lout(){
console.log(store.getState()); //IT SHOW INITIAL STATE
store.dispatch(login());
console.log(store.getState()); //IT SHOWS THAT STATE DID CHANGE
}
////THIS IS THE PROBLEM,
render(){
console.log('rendering')
if(store.getState().isLogged){
return (<MainComponent store={store} />);
}else{
return (
<View style={style.container}>
<Text onPress={this.lout}>
THE FOLLOWING NEVER UPDATE :( !!{store.getState().isLogged?'True':'False'}</Text>
</View>
);
}
}
The only way i could trigger update is by using
store.subscribe(()=>{this.setState({reload:false})});
inside constructor, so that i manually trigger an update state of component to force rerender.
but how can i link both store and component states ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…