我有一个组件,它在我的FE react组件中映射API调用的响应。
API响应看起来像这样:
[
{
time: '1:00pm'
status: 'Success'
},
{
time: '2:00pm'
status: 'Failed: Invalid ID'
},
]
我面临的问题是状态可以有7个不同的值,而不是直接映射状态文本到组件,我被要求映射一个类似的,但稍微基于状态值的文本。
/*
BE Response Text | Text to display on the FE
"Failed: Invalid Portal ID" Failure: Incorrect Username
"Password Lockout" Failure: Account Locked
"Invalid Password" Failure: Incorrect Password
"Passwordless Login Required" Failure: Passwordless login required
"Restricted IP" Failure: Restricted IP
*any other failure message* Failure: Technical Error
"Success" Success
*/
我不知道这里该怎么做,我认为这应该在be上处理,但我被要求在FE上做,不完全确定最好的方法是什么,也许是连锁三元?
目前为止我有什么:
response.map() => {
return (
<div>
{response.status === 'Success'
? response.status
: `Failure ${response.status}`}
</div>
)
})
如何使用一个对象作为所有已知情况的查找表,并退回到"失败:技术错误";
const strings = {
Success: "Success",
"Failed: Invalid Portal ID": "Failure: Incorrect Username";
"Password Lockout": "Failure: Account Locked";
// etc
}
response.map(() => {
return (
<div>
{strings[response.status] || "Failure: Technical Error"}
</div>
)
})