axios 路由,未定义的可选参数

时间:2020-12-30 17:36:05

标签: typescript api axios

所以最终我想为一个可选参数传递一个值,但 'undefined' 被作为字符串插入,而不是像我想要的那样。我在这里缺少什么?默认情况下,路由应该是 /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));

});

1 个答案:

答案 0 :(得分:1)

我只想使用短路评估来测试 showAll 是否为假。如果它是假的,只需使用一个空字符串:

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

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

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