簡體   English   中英

以下 React 測試中的方括號有什么作用?

[英]What do the square brackets in the following React test do?

我正在閱讀“Mastering React Test-Driven Development”,本書推薦的重構之一是將通用測試提取到幫助程序 function 中,方法是更改以下內容:

it('saves existing first name when submitted', async () => {
  expect.hasAssertions();
  render(<CustomerForm {...{firstName: 'Ashley'}} onSubmit={(customer) => 
  expect(customer.firstName).toEqual('Ashley')} />);
  await ReactTestUtils.Simulate.submit(form('customer'));
});

it('saves existing last name when submitted', async () => {
  expect.hasAssertions();
  render(<CustomerForm {...{lastName: 'Jones'}} onSubmit={(customer) => 
  expect(customer.lastName).toEqual('Jones')} />);
  await ReactTestUtils.Simulate.submit(form('customer'));
});

...對此:

const itSavesExistingValueWhenSubmitted = (fieldName, fieldValue) => {
  it('saves existing value when submitted', async () => {
    expect.hasAssertions();
    render(<CustomerForm {...{[fieldName]: fieldValue}} onSubmit={(props) => 
    expect(props[fieldName]).toEqual(fieldValue)} />);
    await ReactTestUtils.Simulate.submit(form('customer'));
  });
}

itSavesExistingValueWhenSubmitted('firstName', 'Ashley');
itSavesExistingValueWhenSubmitted('lastName', 'Jones');

我的問題是關於重構測試中的代碼片段{...{[fieldName]: fieldValue}} 我知道...是后續{} object 的擴展屬性。 但是為什么fieldName需要用方括號括起來呢? 這里的語法是什么?

{...{[fieldName]: fieldValue}}

這里[fieldName]是一個計算屬性名稱。 計算屬性名稱是允許使用變量的值作為屬性名稱的功能。

因此,當您將fieldName作為"firstName"傳遞時, "firstName"將用作屬性名稱,而如果您省略[] ,則屬性名稱實際上是"fieldName"而不是fieldName的值。

這是 ES6 的一個特性。 有關更多詳細信息,請參閱

方括號用於評估 ES6 中的 object 鍵。 您可以這樣做,例如:

var person = {};
var key = "name";

person[key] = "John";

console.log(person); // should print  Object { name="John"}

但是如果你使用的是 ES6,你可以執行以下操作來設置 object:

var key = "name";

var person = {[key]:"John"};

console.log(person); // should print  Object { name="John"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM