【发布时间】:2020-03-04 05:23:29
【问题描述】:
我有这个问题,用户必须在成功登录后重定向到相应的仪表板。假设用户在两个配置文件 "p1" 和 "p2" 中有帐户。登录成功后,我正在制作 fetch API 以查看用户是否有相应配置文件的条目。
1)假设用户在 p1 中有条目,我需要将他重定向到“p1”仪表板;
2) 如果在 p2 中有条目,则将他重定向到“p2”仪表板。
3) 如果 p1 或 p2 中都没有条目,则重定向到配置页面,他可以在其中创建一些条目。
4) 如果在两个配置文件中,则用户将被要求选择相应的仪表板
现在就我而言,我编写的代码没有按预期工作。即使我在“p2”中没有帐户,但在“p1”中有帐户,它也会将我带到配置页面。有人可以帮忙看看这段代码有什么问题吗?
请注意,fetch 调用工作正常!它给了我一系列的项目。如果没有项目,则返回一个空数组
// On login
handleLogin = async () => {
// after successful signin
await Promise.all([
this.setDashboard("p1"),
this.setDashboard("p2"),
]);
this.navigateToDashboards();
};
setDashboard = async (profile) => {
let response, value;
let type = profile;
if (type === "p1") {
response = await this.fetchUserAccounts(type);
value = !!response && response.length ? true : false;
this.setState({ isP1: value });
} else {
response = await this.fetchUserAccounts(type);
value = !!response && response.length ? true : false;
this.setState({ isP2: value });
}
};
fetchUserAccounts = async (type) => {
try {
let response = await fetch({
url: "/fetch/entries",
method: "POST",
body: {
profile: type,
}
);
return response.json();
} catch (error) {
console.log(error);
}
};
navigateToDashboards = () => {
let { isP1, isP2 } = this.state;
if (isP1 && isP2) {
// CODE FOR PROMPTING WHICH DASHBOARD TO GO
} else if (!isP1 && !isP2) {
this.props.history.push("/configpage");
} else if (isP1) {
this.props.history.push("/p1dashboard");
} else if (isP2) {
this.props.history.push("/p2dashboard");
}
};
【问题讨论】:
-
你需要传递一个对象来获取。您所拥有的应该是语法错误。它应该是 fetch({ url: ..., })。注意大括号
-
前提似乎是
fetch()如果服务器返回404会抛出错误。它没有,afaik。 -
@Malvolio 问题与 fetch 无关。我刚刚给出了一个整体的功能。获取工作正常。已更新问题
-
setState(通常)是异步的。在一个反应组件中,你将作用于render。那时您可以确定this.state已更新。
标签: javascript reactjs ecmascript-6 async-await react-router