gpt4 book ai didi

javascript - 使用 react 测试库测试到达路由器

转载 作者:行者123 更新时间:2023-12-01 00:22:26 25 4
gpt4 key购买 nike

通过reach-router使用react测试库 https://testing-library.com/docs/example-reach-router

function renderWithRouter(
ui,
{ route = '/', history = createHistory(createMemorySource(route)) } = {}
)

函数的第二个参数,怀疑是一个对象, {} 。但使用“=”而不是“:”意味着它不是名称-值对。那么它是什么?

另外,两个对象之间的赋值运算符的目的是什么

{ route = '/', history = createHistory(createMemorySource(route)) } = {}

最佳答案

此语法称为 Destructuring assignment设置函数参数的默认值

看看这个例子:

function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
console.log(size, coords, radius);
// do some chart drawing
}

drawChart({
coords: {x: 18, y: 30},
radius: 30
});

In the function signature for drawChart above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: {size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}. You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply call drawChart() without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

返回renderWithRouter函数示例

function renderWithRouter(ui, { route = "/", history = function(){} } = {}) {
console.log(route, history);
}

console.log(renderWithRouter({})) //output: / ƒ (){}

关于javascript - 使用 react 测试库测试到达路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com