【问题标题】:Axios route, undefined optional parameteraxios路由,未定义的可选参数
【发布时间】:2021-04-07 04:56:30
【问题描述】:

所以最终我想为一个可选参数传入一个值,但“未定义”作为一个字符串被插入,而不是像我想要的那样表现。我在这里想念什么?默认情况下,路由应该是 /api/todo/get/ 我知道我可以不使用“showAll”,但要避免尴尬。谢谢。

const getTodos = (showAll = undefined): Thunk<Promise<void>> => (dispatch) => {
  dispatch(setTodos([]));
  return axios.get(`/api/todo/get/${showAll}`).then((res) => {
    dispatch(setTodos(res.data));
  });
};


router.get("/get/:includeCompleted?", (req: Request, res: Response) => {
    const includeCompleted = req.params.includeCompleted;
    console.log(req.params.includeCompleted);
    return database
        .raw<Todo[]>(
            `
        SELECT *
        FROM todo
        WHERE :includeCompleted = 1 OR completedDate IS NULL
    `,
            {includeCompleted: includeCompleted ? 1 : 0}
        )
        .then((data) => res.status(StatusCodes.OK).json(data));

});

【问题讨论】:

    标签: typescript api axios


    【解决方案1】:

    我会使用短路评估来测试showAll 的虚假性。如果是假的,就用一个空字符串:

    return axios.get(`/api/todo/get/${showAll || ''}`)
    

    编辑:正如评论者指出的那样,如果您希望 0false 等值仍被传递给路由,则短路评估可能过于激进。如果是这种情况,请使用 nullish 合并运算符:

    return axios.get(`/api/todo/get/${showAll ?? ''}`)
    

    【讨论】:

    • 我建议使用?? 运算符而不是|| 参考:mariusschulz.com/blog/…
    • 嗯,它肯定可以工作,但我想知道我们希望哪些虚假值认为有效?
    • 我想如果showAll 等于0可能希望使用它而不是空字符串,但我不确定这是否是一个有效的案例
    • 我将无效合并选项更新为答案,感谢@KBeDev
    • 很大程度上取决于端点的具体要求。由于showAll 被隐式定义为any 类型,因此使用??|| 是开发人员的决定
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多