将特定参数传递给函数

3

我有一个函数:

getBooks(page, count, authorId){
      return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
        .then(response => {
            return response.data
        })
}

我正在实现搜索功能,在搜索中我只传递authorId,例如: getBooks(akdjh23) 但是这样做会将akdjh23设置为页面page。即page=akdjh23,但我想要的是authorId=akdjh23
我的问题是,如何在搜索期间只发送authorId,并在一般的获取请求中发送pagecount基于id的搜索:
getBooks(id)

获取所有图书:

get(1, 40) -> page=1, count=40

你不能修改 getBooks 吗? - Addis
why } after authorId} - brk
3个回答

2
您可以通过使用 ES6对象解构 将一个对象传递而不是固定参数并对其进行解构。

例如:

getBooks({ page, count, authorId }){
  return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
    .then(response => {
        return response.data
    })
}

getBooks({ authorId: 45});
getBooks({ page: 'abc', authorId: 67});

1
getBooks(null, null, id)

应该可以解决问题。请注意,您的代码将无法正常工作,因为函数中的页面和计数未定义。


0

你可以改变getBooks的工作方式,传递一个对象而不是多个参数

getBooks({ page, count, authorId })

如果需要,现在只需传递 authorId 即可

getBooks({ authorId: 'authorIdPassed' });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接