我使用了react js和redux,并使用jwt进行了身份验证。
我有一个带下拉菜单的导航栏。此下拉列表仅对经过身份验证的用户可见。下拉项是动态的,应在用户登录后从服务器加载。
但是我不知道我应该在哪里触发api调用来加载下拉项。当我单击"login“时,将触发身份验证操作。在此操作中,我执行身份验证并将一个布尔值返回给一个reducer。然后将"authenticated“状态切换为"true”,并显示下拉列表。现在,应向用户显示下拉项。
但是我什么时候应该加载它们呢?
我的想法是将"load dropdown items“逻辑放入一个reducer中,这样我就可以等待"authenticated”操作。但是逻辑应该在行动中实现,对吗?
你知道我能做什么吗?
发布于 2018-03-08 17:59:30
在redux中,一旦您对用户进行了身份验证,您就可以使用thunk触发另一个api调用,为用户获取信息并为其分派相应的操作。
您可以阅读有关需求的更多信息,并使用thunks here
export function loginUser() {
return async (dispatch, getState) => {
let response = await login(credentials)
//action creator to update boolean that user is logged in
dispatch(loginSuccessful(response)) ;
//action creator to trigger api to fetch drop down data
dispatch(loadDropdownItems(response));
}
}发布于 2018-03-08 19:03:46
我认为当用户输入他的凭据时,你应该从后台处理这个问题。如果用户已通过身份验证,则发送“true”响应,其中包含已通过身份验证的用户的下拉项。
在前端,用户可以使用redux thunk来处理这个问题。Redux thunk是一个帮助你返回函数的中间件。
在componentDidMount中,调用this.props.actions.authAsync()
function authAction() {
return {
type: 'AUTH_SUCCESS'
};
}
function authAsync() {
return dispatch => {
// api call
// based on response show dropdown items
if(response.data.authenticated){
// return dropdown items from response
}
dispatch(authAction());
};
}https://stackoverflow.com/questions/49170219
复制相似问题