【发布时间】:2020-04-25 13:38:48
【问题描述】:
我想在点击按钮时更改DoorState。
发布API更改DoorState后,调用get API检查机器人状态。
其实DoorState 变了。
但console.log(after) 代码不变。为什么?
{
deliveryPost.Delivery.status === 'assigned' &&
(checkDoorState(deliveryPost.Delivery.postId) === 'closed' ? ( <
>
<
button className = "bg-white text-teal-500 py-2 px-4 ml-2 border border-teal-500 rounded hover:bg-teal-500 hover:text-white"
onClick = {
() => clickRobotAction(deliveryPost.Delivery.postId, 'open')
} >
Open Door <
/button> <
/>
) : ( <
>
<
button className = "bg-white text-teal-500 py-2 px-4 ml-2 border border-teal-500 rounded hover:bg-teal-500 hover:text-white"
onClick = {
() => clickRobotAction(deliveryPost.Delivery.postId, 'close')
} >
Close Door <
/button> <
/>
))
}
``
`
`
``
const clickRobotAction = async (postId: string, action: string) => {
const appliedRobot = robots.find(robot => robot.postId === postId);
const {
robotId
} = appliedRobot;
try {
await axios.post(`api/${robotId}/action/${action}`); // DoorState open <=> close
const after = await axios.get('api/robots');
console.log(after); // But not change in this log. Why?
} catch (error) {
console.error(error);
}
};
【问题讨论】:
-
您的代码似乎正确。你确定问题不在后端?你也可以发一下吗?编辑:也许你应该发帖
api/robots/${robotId}/actions/...? -
不应该在
const after = await axios.get('api/robots');中为after分配一个特定的机器人ID(也可能是它的状态)?对api/robots的调用是否返回门状态?? -
是的。 api/robots 有门状态作为响应。
-
我认为 api/robots 不同步。如果我写 setTImeout(() => console.log(after), 1000},它会起作用。
-
axios.get() 是异步的,它返回一个 Promise。 try...catch 是同步的。也许当您
post更改 DoorState 时,您的后端需要执行一个进程(数据库、硬件等),这比您调用get的时间要长。
标签: javascript reactjs typescript next.js