store傳入accountReducer
1.從cookie中獲取id,avatar,nickname.
2.createStore(reducer, initState)傳入reducer,可以在頁面中state.accountReducer.current_account獲取
const middleware = routerMiddleware(browserHistory);
let initState = {};if(Cookie.hasItem("id")){initState.accountReducer = {current_account:{id: Cookie.getItem("id"),avatar: Cookie.getItem("avatar"),nickname: Cookie.getItem("nickname")}}
}
let store = createStore(reducer,initState,compose(applyMiddleware(thunkMiddleware, middleware),(window.RAILS_ENV === 'development' && window.devToolsExtension) ? window.devToolsExtension() : f=>f)
);
SignInPopup組件
1.通過this.props.sign_in_popup_visible是true或false來判斷是否顯示登陸框.
true則顯示,false則隱藏.
2.隱藏登陸框,this.setSignVisible(false);,調用this.props.dispatch(setSignInPopupVisible(visible));
3.Action:
function setSignInPopupVisible(value){
return {type: SET_SIGN_IN_POPUP_VISIBLE,value: value
};
}
4.reducer:
function current_account(state={}, action){
switch(action.type){case SET_ACCOUNT:return Object.assign({}, state, action.data);case INIT_ACCOUNT:return action.data;default:return state;
}
}
{this.props.sign_in_popup_visible?<Modal onClose={this.handleSignInPopupClose} mode="simple"><SignInPopup /></Modal>:""}
sign_in_popup_visible: state.accountReducer.sign_in_popup_visible
setSignVisible: function(visible) {this.props.dispatch(setSignInPopupVisible(visible));
}function setSignInPopupVisible(value){return {type: SET_SIGN_IN_POPUP_VISIBLE,value: value};}
checkStatus
1.current_account從原始狀態init_state獲取.
如果初次登陸沒有cookie,則調用this.setSignVisible(true),顯示登陸框.
如果有cookie信息,則return true,執行下面的代碼.
this.props.dispatch(takeRedPacket(id));
else if (xhr.status === 401) {
dispatch(setSignInPopupVisible(true));
}
checkStatus: function(){const {current_account} = this.props;if(!current_account.id){this.setSignVisible(true);return false;}else{return true;}
}