Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(cn): translate reference/react-dom/hooks/useFormState into Chinese #1367

Merged
merged 17 commits into from
Nov 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 49 additions & 45 deletions src/content/reference/react-dom/hooks/useFormState.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ canary: true

<Canary>

The `useFormState` Hook is currently only available in React's canary and experimental channels. Learn more about [release channels here](/community/versioning-policy#all-release-channels). In addition, you need to use a framework that supports [React Server Components](/reference/react/use-client) to get the full benefit of `useFormState`.
`useFormState` Hook 当前仅在 React canary experimental 渠道中可用。请点此了解更多关于 [React 发布渠道](/community/versioning-policy#all-release-channels) 的信息。此外,需要一款完全支持 [React 服务器组件](/reference/react/use-client) 特性的框架才可以使用 `useFormState` 的所有特性。

</Canary>

<Intro>

`useFormState` is a Hook that allows you to update state based on the result of a form action.
`useFormState` 是一个可以根据某个表单动作的结果更新 state 的 Hook。

```js
const [state, formAction] = useFormState(fn, initialState);
Expand All @@ -23,13 +23,13 @@ const [state, formAction] = useFormState(fn, initialState);

---

## Reference {/*reference*/}
## 参考 {/*reference*/}

### `useFormState(action, initialState)` {/*useformstate*/}

{/* TODO T164397693: link to actions documentation once it exists */}

Call `useFormState` at the top level of your component to create component state that is updated [when a form action is invoked](/reference/react-dom/components/form). You pass `useFormState` an existing form action function as well as an initial state, and it returns a new action that you use in your form, along with the latest form state. The latest form state is also passed to the function that you provided.
在组件的顶层调用 `useFormState` 即可创建一个随 [表单动作被调用](/reference/react-dom/components/form) 而更新的 state。在调用 `useFormState` 时在参数中传入现有的表单动作函数以及一个初始状态,它就会返回一个新的 action 函数和一个 form state 以供在 form 中使用。这个新的 form state 也会作为参数传入提供的表单动作函数。

```js
import { useFormState } from "react-dom";
Expand All @@ -43,44 +43,44 @@ function StatefulForm({}) {
return (
<form>
{state}
<button formAction={formAction}>Increment</button>
<button formAction={formAction}>+1</button>
</form>
)
}
```

The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.
form state 是一个只在表单被提交触发 action 后才会被更新的值。如果该表单没有被提交,该值会保持传入的初始值不变。

If used with a Server Action, `useFormState` allows the server's response from submitting the form to be shown even before hydration has completed.
如果配合 Server Actions 一起使用,`useFormState` 允许与表单交互的服务器的返回值在 hydration 完成前显示。

[See more examples below.](#usage)
[请参阅下方更多示例](#usage)

#### Parameters {/*parameters*/}
#### 参数 {/*parameters*/}

* `fn`: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the `initialState` that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
* `initialState`: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
* `fn`:当按钮被按下或者表单被提交时触发的函数。当函数被调用时,该函数会接收到表单的上一个 state(初始值为传入的 `initialState` 参数,否则为上一次执行完该函数的结果)作为函数的第一个参数,余下参数为普通表单动作接到的参数。
* `initialState`state 的初始值。任何可序列化的值都可接收。当 action 被调用一次后该参数会被忽略。

{/* TODO T164397693: link to serializable values docs once it exists */}

#### Returns {/*returns*/}
#### 返回值 {/*returns*/}

`useFormState` returns an array with exactly two values:
`useFormState` 返回一个包含两个值的数组:

1. The current state. During the first render, it will match the `initialState` you have passed. After the action is invoked, it will match the value returned by the action.
2. A new action that you can pass as the `action` prop to your `form` component or `formAction` prop to any `button` component within the form.
1. 当前的 state。第一次渲染期间,该值为传入的 `initialState` 参数值。在 action 被调用后该值会变为 action 的返回值。
2. 一个新的 action 函数用于在你的 `form` 组件的 `action` 参数或表单中任意一个 `button` 组件的 `formAction` 参数中传递。

#### Caveats {/*caveats*/}
#### 注意 {/*caveats*/}

* When used with a framework that supports React Server Components, `useFormState` lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state.
* The function passed to `useFormState` receives an extra argument, the previous or initial state, as its first argument. This makes its signature different than if it were used directly as a form action without using `useFormState`.
* 在支持 React 服务器组件的框架中使用该功能时,`useFormState` 允许表单在服务器渲染阶段时获得部分交互性。当不使用服务器组件时,它的特性与本地 state 相同。
* 与直接通过表单动作调用的函数不同,传入 `useFormState` 的函数被调用时,会多传入一个代表 state 的上一个值或初始值的参数作为该函数的第一个参数。

---

## Usage {/*usage*/}
## 用法 {/*usage*/}

### Using information returned by a form action {/*using-information-returned-by-a-form-action*/}
### 使用某个表单动作返回的信息 {/*using-information-returned-by-a-form-action*/}

Call `useFormState` at the top level of your component to access the return value of an action from the last time a form was submitted.
在组件的顶层调用 `useFormState` 以获取上一次表单被提交时触发的 action 的返回值。

```js [[1, 5, "state"], [2, 5, "formAction"], [3, 5, "action"], [4, 5, "null"], [2, 8, "formAction"]]
import { useFormState } from 'react-dom';
Expand All @@ -97,14 +97,14 @@ function MyComponent() {
}
```

`useFormState` returns an array with exactly two items:
`useFormState` 返回一个包含两个值的数组:

1. The <CodeStep step={1}>current state</CodeStep> of the form, which is initially set to the <CodeStep step={4}>initial state</CodeStep> you provided, and after the form is submitted is set to the return value of the <CodeStep step={3}>action</CodeStep> you provided.
2. A <CodeStep step={2}>new action</CodeStep> that you pass to `<form>` as its `action` prop.
1. 该表单的 <CodeStep step={1}>当前 state</CodeStep>,初始值为提供的 <CodeStep step={4}>初始 state</CodeStep>,当表单被提交后则改为传入的 <CodeStep step={3}>action</CodeStep> 的返回值。
2. 传入 `<form>` 标签的 `action` 属性的 <CodeStep step={2}> action</CodeStep>

When the form is submitted, the <CodeStep step={3}>action</CodeStep> function that you provided will be called. Its return value will become the new <CodeStep step={1}>current state</CodeStep> of the form.
表单被提交后,传入的 <CodeStep step={3}>action</CodeStep> 函数会被执行。返回值将会作为该表单的新的 <CodeStep step={1}>当前 state</CodeStep>

The <CodeStep step={3}>action</CodeStep> that you provide will also receive a new first argument, namely the <CodeStep step={1}>current state</CodeStep> of the form. The first time the form is submitted, this will be the <CodeStep step={4}>initial state</CodeStep> you provided, while with subsequent submissions, it will be the return value from the last time the action was called. The rest of the arguments are the same as if `useFormState` had not been used
传入的 <CodeStep step={3}>action</CodeStep> 接受到的第一个参数将会变为该表单的 <CodeStep step={1}>当前 state</CodeStep>。当表单第一次被提交时将会传入提供的 <CodeStep step={4}>初始 state</CodeStep>,之后都将传入上一次调用 <CodeStep step={3}>action</CodeStep> 函数的返回值。余下参数与未使用 `useFormState` 前接受的参数别无二致<sup><a href="#note1">[1]</a></sup>。

```js [[3, 1, "action"], [1, 1, "currentState"]]
function action(currentState, formData) {
Expand All @@ -113,11 +113,11 @@ function action(currentState, formData) {
}
```

<Recipes titleText="Display information after submitting a form" titleId="display-information-after-submitting-a-form">
<Recipes titleText="提交表单后展示信息" titleId="display-information-after-submitting-a-form">

#### Display form errors {/*display-form-errors*/}
#### 展示表单错误 {/*display-form-errors*/}

To display messages such as an error message or toast that's returned by a Server Action, wrap the action in a call to `useFormState`.
将 action 包裹进 `useFormState` 即可展示诸如错误信息或 Server Actions 返回的 toast 等信息。

<Sandpack>

Expand All @@ -132,7 +132,7 @@ function AddToCartForm({itemID, itemTitle}) {
<form action={formAction}>
<h2>{itemTitle}</h2>
<input type="hidden" name="itemID" value={itemID} />
<button type="submit">Add to Cart</button>
<button type="submit">加入购物车</button>
{message}
</form>
);
Expand All @@ -141,8 +141,8 @@ function AddToCartForm({itemID, itemTitle}) {
export default function App() {
return (
<>
<AddToCartForm itemID="1" itemTitle="JavaScript: The Definitive Guide" />
<AddToCartForm itemID="2" itemTitle="JavaScript: The Good Parts" />
<AddToCartForm itemID="1" itemTitle="JavaScript:权威指南" />
<AddToCartForm itemID="2" itemTitle="JavaScript:优点荟萃" />
</>
)
}
Expand All @@ -154,9 +154,9 @@ export default function App() {
export async function addToCart(prevState, queryData) {
const itemID = queryData.get('itemID');
if (itemID === "1") {
return "Added to cart";
return "已加入购物车";
} else {
return "Couldn't add to cart: the item is sold out.";
return "无法加入购物车:商品已售罄";
}
}
```
Expand Down Expand Up @@ -188,9 +188,9 @@ form button {

<Solution />

#### Display structured information after submitting a form {/*display-structured-information-after-submitting-a-form*/}
#### 提交表单后展示结构性数据 {/*display-structured-information-after-submitting-a-form*/}

The return value from a Server Action can be any serializable value. For example, it could be an object that includes a boolean indicating whether the action was successful, an error message, or updated information.
Server Actions 的返回值可以为任意可序列化的值。例如,可以返回一个实例,该实例携带一个 boolean 类型的属性表示操作是否成功,同时附带错误信息或更新消息。

<Sandpack>

Expand All @@ -205,15 +205,15 @@ function AddToCartForm({itemID, itemTitle}) {
<form action={formAction}>
<h2>{itemTitle}</h2>
<input type="hidden" name="itemID" value={itemID} />
<button type="submit">Add to Cart</button>
<button type="submit">加入购物车</button>
{formState?.success &&
<div className="toast">
Added to cart! Your cart now has {formState.cartSize} items.
成功加入购物车!当前购物车中共有 {formState.cartSize} 件商品。
</div>
}
{formState?.success === false &&
<div className="error">
Failed to add to cart: {formState.message}
加入购物车失败:{formState.message}
</div>
}
</form>
Expand All @@ -223,8 +223,8 @@ function AddToCartForm({itemID, itemTitle}) {
export default function App() {
return (
<>
<AddToCartForm itemID="1" itemTitle="JavaScript: The Definitive Guide" />
<AddToCartForm itemID="2" itemTitle="JavaScript: The Good Parts" />
<AddToCartForm itemID="1" itemTitle="JavaScript:权威指南" />
<AddToCartForm itemID="2" itemTitle="JavaScript:优点荟萃" />
</>
)
}
Expand All @@ -243,7 +243,7 @@ export async function addToCart(prevState, queryData) {
} else {
return {
success: false,
message: "The item is sold out.",
message: "商品已售罄",
};
}
}
Expand Down Expand Up @@ -278,14 +278,18 @@ form button {

</Recipes>

## Troubleshooting {/*troubleshooting*/}
## 疑难解答 {/*troubleshooting*/}

### My action can no longer read the submitted form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}
### 我的 action 无法再获取提交的 form data {/*my-action-can-no-longer-read-the-submitted-form-data*/}

When you wrap an action with `useFormState`, it gets an extra argument *as its first argument*. The submitted form data is therefore its *second* argument instead of its first as it would usually be. The new first argument that gets added is the current state of the form.
当使用 `useFormState` 包裹 action 时,第一个参数变为了 form 的当前 state,提交的表单数据被顺移到了第二个参数中,与直接使用表单动作是不同的。

```js
function action(currentState, formData) {
// ...
}
```

**译注:**

<a name="note1"></a> [1] 这里的意思是原来的第一个参数被顺移为第二个参数,第二个参数被顺移为第三个参数,以此类推
Loading