我是redux / react的新手,并尝试整理登录页面。但由于某种原因,异步参数中的代码未运行。我试着写它,所以我不需要输入一堆.then语句。我的代码如下。
export function signIn (email, password) {
console.log('trying to login');
return async function (dispatch) {
const error = validateCredentials(email, password);
if (error) {
return error;
}
try {
console.log('gather credentials');
const geoipjson = await geoip();
console.log(geoipjson);
const ip = geoipjson.ip;
console.log(ip);
const country = geoipjson.country_name;
console.log(country);
const fp = await getFingerprint();
console.log(fp);
const res = await authenticateUser(email, password, ip, country, fp);
if (!res.jwt) {
return res;
}
const update_error = await updateLoginStamp(res.jwt);
if (update_error) {
return update_error;
}
setCookie("jwt", res.jwt);
console.log('user authenticated');
dispatch({type: USER_AUTHENTICATED});
history.push('/');
return null;
} catch (error) {
console.log('authentication error');
dispatch({type: AUTHENTICATION_ERROR, error});
return error;
}
}
答案 0 :(得分:0)
Is it logging an error at the beginning? Also, can you post the validateCredentials code?
const error = validateCredentials(email, password);
if (error) {
console.log('Error: ', error);
return error;
}
答案 1 :(得分:0)
实际上,我在博客条目的帮助下找到了解决方案。之后我意识到了代码,
return async function (dispatch) { ... }
没有被召唤。我从主app.js调用此函数,但需要" dispatch"从进行调用的组件,到使用中间件thunk。我没有理解整个答案,但它与绑定到动作器有关。这里的博客处理得非常好,是我能找到的最好的解决方案。
import {connect} from "react-redux";
import {action1, action2} from "myActions";
const MyComponent = (props) => (
<div>
<button onClick={props.action1}>Do first action</button>
<button onClick={props.action2}>Do second action</button>
</div>
)
// Passing an object full of actions will automatically run each action
// through the bindActionCreators utility, and turn them into props
export default connect(null, {action1, action2})(MyComponent);
可以找到完整的说明和博客条目here。这为我解决了一个巨大的问题,并且在我看来是以一种很好的方式完成的。