From 73443f31453e0773f1a226ad0761bb4c8adf86bc Mon Sep 17 00:00:00 2001 From: Soichiro Miki Date: Wed, 13 Sep 2023 20:11:50 +0900 Subject: [PATCH] Translate (legacy, class) "Component" --- src/content/reference/react/Component.md | 584 +++++++++++------------ 1 file changed, 292 insertions(+), 292 deletions(-) diff --git a/src/content/reference/react/Component.md b/src/content/reference/react/Component.md index 6174cd753..c2b0543ee 100644 --- a/src/content/reference/react/Component.md +++ b/src/content/reference/react/Component.md @@ -4,13 +4,13 @@ title: Component -We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives) +クラスの代わりに関数でコンポーネントを定義することを推奨します。[移行方法はこちら](#alternatives)。 -`Component` is the base class for the React components defined as [JavaScript classes.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) Class components are still supported by React, but we don't recommend using them in new code. +`Component` は React コンポーネントの基底クラスであり、[JavaScript のクラス](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)として定義されています。React は現在でもクラスコンポーネントをサポートしていますが、新しいコードでの使用は推奨されません。 ```js class Greeting extends Component { @@ -26,11 +26,11 @@ class Greeting extends Component { --- -## Reference {/*reference*/} +## リファレンス {/*reference*/} ### `Component` {/*component*/} -To define a React component as a class, extend the built-in `Component` class and define a [`render` method:](#render) +クラスとして React コンポーネントを定義するには、組み込みの `Component` クラスを継承し、[`render` メソッド](#render)を定義します。 ```js import { Component } from 'react'; @@ -42,17 +42,17 @@ class Greeting extends Component { } ``` -Only the `render` method is required, other methods are optional. +`render` メソッドのみが必須です。他のメソッドはオプションです。 -[See more examples below.](#usage) +[さらに例を読む](#usage) --- ### `context` {/*context*/} -The [context](/learn/passing-data-deeply-with-context) of a class component is available as `this.context`. It is only available if you specify *which* context you want to receive using [`static contextType`](#static-contexttype) (modern) or [`static contextTypes`](#static-contexttypes) (deprecated). +クラスコンポーネントでは[コンテクスト](/learn/passing-data-deeply-with-context)を `this.context` の形で利用できます。これは、[`static contextType`](#static-contexttype)(現行版)または [`static contextTypes`](#static-contexttypes)(非推奨)を使用して受け取りたいコンテクストを指定した場合にのみ利用できます。 -A class component can only read one context at a time. +クラスコンポーネントは、一度に 1 種類のコンテクストしか読み取ることができません。 ```js {2,5} class Button extends Component { @@ -73,9 +73,9 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +クラスコンポーネントで `this.context` を読み取ることは、関数コンポーネントで [`useContext`](/reference/react/useContext) を用いることと同等です。 -[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -83,7 +83,7 @@ Reading `this.context` in class components is equivalent to [`useContext`](/refe ### `props` {/*props*/} -The props passed to a class component are available as `this.props`. +クラスコンポーネントに渡された props は `this.props` の形で利用できます。 ```js {3} class Greeting extends Component { @@ -97,9 +97,9 @@ class Greeting extends Component { -Reading `this.props` in class components is equivalent to [declaring props](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component) in function components. +クラスコンポーネントで `this.props` を読み取ることは、関数コンポーネントで [props を宣言する](/learn/passing-props-to-a-component#step-2-read-props-inside-the-child-component)ことと同等です。 -[See how to migrate.](#migrating-a-simple-component-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-simple-component-from-a-class-to-a-function) @@ -109,17 +109,17 @@ Reading `this.props` in class components is equivalent to [declaring props](/lea -This API will be removed in a future major version of React. [Use `createRef` instead.](/reference/react/createRef) +この API は React の将来のメジャーバージョンで削除されます。[代わりに `createRef` を使用してください](/reference/react/createRef)。 -Lets you access [legacy string refs](https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs) for this component. +このコンポーネントの[レガシーな文字列形式 ref](https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs) にアクセスできます。 --- ### `state` {/*state*/} -The state of a class component is available as `this.state`. The `state` field must be an object. Do not mutate the state directly. If you wish to change the state, call `setState` with the new state. +クラスコンポーネントの state は `this.state` の形で利用できます。`state` フィールドはオブジェクトでなければなりません。state を直接書き換えてはいけません。state を変更したい場合は、新しい state を引数にして `setState` を呼び出します。 ```js {2-4,7-9,18} class Counter extends Component { @@ -148,9 +148,9 @@ class Counter extends Component { -Defining `state` in class components is equivalent to calling [`useState`](/reference/react/useState) in function components. +クラスコンポーネントで `state` を定義することは、関数コンポーネントで [`useState`](/reference/react/useState) を呼び出すことと同等です。 -[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -158,7 +158,7 @@ Defining `state` in class components is equivalent to calling [`useState`](/refe ### `constructor(props)` {/*constructor*/} -The [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) runs before your class component *mounts* (gets added to the screen). Typically, a constructor is only used for two purposes in React. It lets you declare state and [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) your class methods to the class instance: +[コンストラクタ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor)は、クラスコンポーネントが*マウント*(画面に追加)される前に実行されます。通常 React では、コンストラクタは 2 つの目的でのみ利用されます。state の宣言と、クラスメソッドのクラスインスタンスへの[バインド](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind)です。 ```js {2-6} class Counter extends Component { @@ -173,7 +173,7 @@ class Counter extends Component { } ``` -If you use modern JavaScript syntax, constructors are rarely needed. Instead, you can rewrite this code above using the [public class field syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) which is supported both by modern browsers and tools like [Babel:](https://babeljs.io/) +モダンな JavaScript 構文を使用している場合、コンストラクタはほとんど必要ありません。代わりに上記のコードは、モダンブラウザや [Babel](https://babeljs.io/) などのツールでサポートされている[パブリッククラスフィールド構文](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields)を使用して書き直すことができます。 ```js {2,4} class Counter extends Component { @@ -184,31 +184,31 @@ class Counter extends Component { } ``` -A constructor should not contain any side effects or subscriptions. +コンストラクタには副作用やサブスクリプション(subscription, イベント登録や外部データ購読)を一切含めてはいけません。 -#### Parameters {/*constructor-parameters*/} +#### 引数 {/*constructor-parameters*/} -* `props`: The component's initial props. +* `props`: コンポーネントの初期 props。 -#### Returns {/*constructor-returns*/} +#### 返り値 {/*constructor-returns*/} -`constructor` should not return anything. +`constructor` は何も返してはいけません。 -#### Caveats {/*constructor-caveats*/} +#### 注意点 {/*constructor-caveats*/} -* Do not run any side effects or subscriptions in the constructor. Instead, use [`componentDidMount`](#componentdidmount) for that. +* コンストラクタ内で副作用やサブスクリプションを実行しないでください。代わりに [`componentDidMount`](#componentdidmount) を使用してください。 -* Inside a constructor, you need to call `super(props)` before any other statement. If you don't do that, `this.props` will be `undefined` while the constructor runs, which can be confusing and cause bugs. +* コンストラクタ内では、他のすべてのステートメントの前に `super(props)` を呼び出す必要があります。これを行わないと、コンストラクタが実行されている間 `this.props` が `undefined` になるため、混乱を招きバグの原因となる可能性があります。 -* Constructor is the only place where you can assign [`this.state`](#state) directly. In all other methods, you need to use [`this.setState()`](#setstate) instead. Do not call `setState` in the constructor. +* [`this.state`](#state) を直接セットして良い唯一の場所がコンストラクタです。他のすべてのメソッド内では、代わりに [`this.setState()`](#setstate) を使用する必要があります。コンストラクタ内で `setState` を呼び出さないでください。 -* When you use [server rendering,](/reference/react-dom/server) the constructor will run on the server too, followed by the [`render`](#render) method. However, lifecycle methods like `componentDidMount` or `componentWillUnmount` will not run on the server. +* [サーバレンダリング](/reference/react-dom/server)を使用する場合、コンストラクタもサーバ上で実行され、その後に [`render`](#render) メソッドが続きます。ただし、`componentDidMount` や `componentWillUnmount` のようなライフサイクルメソッドはサーバ上では実行されません。 -* When [Strict Mode](/reference/react/StrictMode) is on, React will call `constructor` twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the `constructor`. +* [Strict Mode](/reference/react/StrictMode) が有効の場合、React は開発環境において `constructor` を 2 回呼び出し、2 つのインスタンスのうち 1 つを破棄します。これにより、`constructor` 外に移動するべき偶発的な副作用に気づきやすくなります。 -There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state) +関数コンポーネントには `constructor` とまったく同等のものは存在しません。関数コンポーネントで state を宣言するには [`useState`](/reference/react/useState) を呼び出します。初期 state の再計算を避けたい場合は [`useState` に関数を渡します](/reference/react/useState#avoiding-recreating-the-initial-state)。 @@ -216,31 +216,31 @@ There is no exact equivalent for `constructor` in function components. To declar ### `componentDidCatch(error, info)` {/*componentdidcatch*/} -If you define `componentDidCatch`, React will call it when some child component (including distant children) throws an error during rendering. This lets you log that error to an error reporting service in production. +`componentDidCatch` を定義すると、子コンポーネント(遠くの子を含む)がレンダー中にエラーをスローしたときに React がそれを呼び出します。これにより、本番環境でそのエラーをエラーレポートサービスにログとして記録することができます。 -Typically, it is used together with [`static getDerivedStateFromError`](#static-getderivedstatefromerror) which lets you update state in response to an error and display an error message to the user. A component with these methods is called an *error boundary.* +通常これは、エラーに反応して state を更新し、ユーザにエラーメッセージを表示するための [`static getDerivedStateFromError`](#static-getderivedstatefromerror) と一緒に使用されます。これらのメソッドを持つコンポーネントのことを*エラーバウンダリ (error boundary)* と呼びます。 -[See an example.](#catching-rendering-errors-with-an-error-boundary) +[例を見る](#catching-rendering-errors-with-an-error-boundary) -#### Parameters {/*componentdidcatch-parameters*/} +#### 引数 {/*componentdidcatch-parameters*/} -* `error`: The error that was thrown. In practice, it will usually be an instance of [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) but this is not guaranteed because JavaScript allows to [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) any value, including strings or even `null`. +* `error`: スローされたエラー。現実的には通常 [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) のインスタンスになりますが、このことは保証されていません。JavaScript では文字列や `null` すら含む、任意の値を [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) することが許されているためです。 -* `info`: An object containing additional information about the error. Its `componentStack` field contains a stack trace with the component that threw, as well as the names and source locations of all its parent components. In production, the component names will be minified. If you set up production error reporting, you can decode the component stack using sourcemaps the same way as you would do for regular JavaScript error stacks. +* `info`: エラーに関する追加情報を含むオブジェクト。その `componentStack` フィールドには、スローしたコンポーネントとそのすべての親コンポーネントの名前およびソース上の位置を含んだスタックトレースが含まれます。本番環境では、コンポーネント名はミニファイされています。本番環境用にエラーレポートを設定する場合は、通常の JavaScript エラースタックと同じように、ソースマップを使用してコンポーネントスタックをデコードできます。 -#### Returns {/*componentdidcatch-returns*/} +#### 返り値 {/*componentdidcatch-returns*/} -`componentDidCatch` should not return anything. +`componentDidCatch` は何も返してはいけません。 -#### Caveats {/*componentdidcatch-caveats*/} +#### 注意点 {/*componentdidcatch-caveats*/} -* In the past, it was common to call `setState` inside `componentDidCatch` in order to update the UI and display the fallback error message. This is deprecated in favor of defining [`static getDerivedStateFromError`.](#static-getderivedstatefromerror) +* 以前は、UI を更新してフォールバックのエラーメッセージを表示するために `componentDidCatch` 内で `setState` を呼び出すことが一般的でした。これは非推奨となり、代わりに [`static getDerivedStateFromError`](#static-getderivedstatefromerror) を定義することが推奨されています。 -* Production and development builds of React slightly differ in the way `componentDidCatch` handles errors. In development, the errors will bubble up to `window`, which means that any `window.onerror` or `window.addEventListener('error', callback)` will intercept the errors that have been caught by `componentDidCatch`. In production, instead, the errors will not bubble up, which means any ancestor error handler will only receive errors not explicitly caught by `componentDidCatch`. +* React の本番用ビルドと開発用ビルドでは、`componentDidCatch` がエラーを処理する方法がわずかに異なります。開発中は、エラーが `window` にまでバブルアップするため、`window.onerror` や `window.addEventListener('error', callback)` といったコードが `componentDidCatch` によってキャッチされたエラーを捕まえることができます。一方で本番環境ではエラーはバブルアップしないため、祖先のエラーハンドラは `componentDidCatch` によって明示的にキャッチされなかったエラーのみを受け取ります。 -There is no direct equivalent for `componentDidCatch` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, you can use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that for you. +関数コンポーネントには `componentDidCatch` に直接対応するものはまだありません。クラスコンポーネントの作成をなるべく避けたい場合は、上記のような `ErrorBoundary` コンポーネントを 1 つだけ書いてアプリ全体で使用します。あるいはこれを代わりにやってくれる [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) パッケージを使用することもできます。 @@ -248,9 +248,9 @@ There is no direct equivalent for `componentDidCatch` in function components yet ### `componentDidMount()` {/*componentdidmount*/} -If you define the `componentDidMount` method, React will call it when your component is added *(mounted)* to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate the DOM nodes. +`componentDidMount` メソッドを定義すると、コンポーネントが画面に追加(*マウント*)されたときに React がそれを呼び出します。一般的にはここで、データ取得、サブスクリプション設定や DOM ノードの操作を開始します。 -If you implement `componentDidMount`, you usually need to implement other lifecycle methods to avoid bugs. For example, if `componentDidMount` reads some state or props, you also have to implement [`componentDidUpdate`](#componentdidupdate) to handle their changes, and [`componentWillUnmount`](#componentwillunmount) to clean up whatever `componentDidMount` was doing. +`componentDidMount` を実装する場合、通常はバグを避けるために他のライフサイクルメソッドも実装する必要があります。例えば、`componentDidMount` が何らかの state や props を読み取る場合はそれらに変更があった場合に処理するために [`componentDidUpdate`](#componentdidupdate) を実装する必要があり、`componentDidMount` が実行したことをクリーンアップするためには [`componentWillUnmount`](#componentwillunmount) を実装する必要があります。 ```js {6-8} class ChatRoom extends Component { @@ -280,27 +280,27 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[他の例を見る](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentdidmount-parameters*/} +#### 引数 {/*componentdidmount-parameters*/} -`componentDidMount` does not take any parameters. +`componentDidMount` は引数を受け取りません。 -#### Returns {/*componentdidmount-returns*/} +#### 返り値 {/*componentdidmount-returns*/} -`componentDidMount` should not return anything. +`componentDidMount` は何も返してはいけません。 -#### Caveats {/*componentdidmount-caveats*/} +#### 注意点 {/*componentdidmount-caveats*/} -- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call `componentDidMount`, then immediately call [`componentWillUnmount`,](#componentwillunmount) and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does. +- [Strict Mode](/reference/react/StrictMode) がオンの場合、React は開発中に `componentDidMount` を呼び出し、直後に [`componentWillUnmount`](#componentwillunmount) を呼び出し、そして再度 `componentDidMount` を呼び出します。これにより、`componentWillUnmount` の実装を忘れた場合や、そのロジックが `componentDidMount` の挙動と正しく「鏡のように対応」していない場合に気づきやすくなります。 -- Although you may call [`setState`](#setstate) immediately in `componentDidMount`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the [`constructor`](#constructor) instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position. +- `componentDidMount` の中で直ちに [`setState`](#setstate) を呼び出すことは可能ですが、可能な限り避けるべきです。これは追加のレンダーを引き起こしますが、ブラウザが画面を更新する前に発生します。このため、このケースでは [`render`](#render) が 2 回呼び出されはしますが、ユーザは中途半端な state を見ずに済みます。このパターンはしばしばパフォーマンスの問題を引き起こすため、注意して使用してください。ほとんどの場合、初期 state を [`constructor`](#constructor) で代入できるはずです。ただし、モーダルやツールチップのような場合は、何らかの DOM ノードの位置やサイズに依存する要素をレンダーするのに DOM ノードの測定を行うため、これが必要になることがあります。 -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +多くのユースケースにおいて、クラスコンポーネントで `componentDidMount`、`componentDidUpdate`、`componentWillUnmount` をまとめて定義することは、関数コンポーネントで [`useEffect`](/reference/react/useEffect) を呼び出すことと同等です。ブラウザの描画前にコードを実行することが重要となる稀なケースでは、[`useLayoutEffect`](/reference/react/useLayoutEffect) がより近いものになります。 -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -308,9 +308,9 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com ### `componentDidUpdate(prevProps, prevState, snapshot?)` {/*componentdidupdate*/} -If you define the `componentDidUpdate` method, React will call it immediately after your component has been re-rendered with updated props or state. This method is not called for the initial render. +`componentDidUpdate` メソッドを定義すると、コンポーネントが更新後の props や state で再レンダーされた直後に React がそれを呼び出します。このメソッドは初回レンダーでは呼び出されません。 -You can use it to manipulate the DOM after an update. This is also a common place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). Typically, you'd use it together with [`componentDidMount`](#componentdidmount) and [`componentWillUnmount`:](#componentwillunmount) +更新後に DOM を操作するためにこれを使用することができます。これはまた、ネットワークリクエストを行う一般的な場所でもありますが、現在の props を前の props と比較する必要があります(例えば props が変更されていない場合、新しいネットワークリクエストは必要ないかもしれません)。通常、[`componentDidMount`](#componentdidmount) や [`componentWillUnmount`](#componentwillunmount) と一緒に使用します。 ```js {10-18} class ChatRoom extends Component { @@ -340,34 +340,34 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[他の例を見る](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentdidupdate-parameters*/} +#### 引数 {/*componentdidupdate-parameters*/} -* `prevProps`: Props before the update. Compare `prevProps` to [`this.props`](#props) to determine what changed. +* `prevProps`: 更新前の props。`prevProps` と [`this.props`](#props) を比較して何が変わったかを判断します。 -* `prevState`: State before the update. Compare `prevState` to [`this.state`](#state) to determine what changed. +* `prevState`: 更新前の state。`prevState` と [`this.state`](#state) を比較して何が変わったかを判断します。 -* `snapshot`: If you implemented [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate), `snapshot` will contain the value you returned from that method. Otherwise, it will be `undefined`. +* `snapshot`: [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) を実装した場合、`snapshot` にはそのメソッドから返された値が含まれます。それ以外の場合は `undefined` になります。 -#### Returns {/*componentdidupdate-returns*/} +#### 返り値 {/*componentdidupdate-returns*/} -`componentDidUpdate` should not return anything. +`componentDidUpdate` は何も返してはいけません。 -#### Caveats {/*componentdidupdate-caveats*/} +#### 注意点 {/*componentdidupdate-caveats*/} -- `componentDidUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- [`shouldComponentUpdate`](#shouldcomponentupdate) が定義されており、それが `false` を返す場合、`componentDidUpdate` は呼び出されません。 -- The logic inside `componentDidUpdate` should usually be wrapped in conditions comparing `this.props` with `prevProps`, and `this.state` with `prevState`. Otherwise, there's a risk of creating infinite loops. +- `componentDidUpdate` 内のロジックは通常、`this.props` と `prevProps`、`this.state` と `prevState` を比較する条件文でラップする必要があります。そうでなければ、無限ループを作り出すリスクがあります。 -- Although you may call [`setState`](#setstate) immediately in `componentDidUpdate`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. This pattern often causes performance issues, but it may be necessary for rare cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position. +- `componentDidUpdate` の中で直ちに [`setState`](#setstate) を呼び出すことは可能ですが、可能な限り避けるべきです。これは追加のレンダーを引き起こしますが、ブラウザが画面を更新する前に発生します。このため、このケースでは [`render`](#render) が 2 回呼び出されはしますが、ユーザは中途半端な state を見ずに済みます。このパターンはしばしばパフォーマンスの問題を引き起こします。ただし、モーダルやツールチップのようなレアなケースでは、何らかの DOM ノードの位置やサイズに依存する要素をレンダーするのに DOM ノードの測定を行うため、これが必要になることがあります。 -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +多くのユースケースにおいて、クラスコンポーネントで `componentDidMount`、`componentDidUpdate`、`componentWillUnmount` をまとめて定義することは、関数コンポーネントで [`useEffect`](/reference/react/useEffect) を呼び出すことと同等です。ブラウザの描画前にコードを実行することが重要となる稀なケースでは、[`useLayoutEffect`](/reference/react/useLayoutEffect) がより近いものになります。 -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) --- @@ -376,9 +376,9 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com -This API has been renamed from `componentWillMount` to [`UNSAFE_componentWillMount`.](#unsafe_componentwillmount) The old name has been deprecated. In a future major version of React, only the new name will work. +この API は `componentWillMount` から [`UNSAFE_componentWillMount`](#unsafe_componentwillmount) に名前が変更されました。古い名前は非推奨となりました。React の将来のメジャーバージョンでは、新しい名前のみが機能します。 -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +自動的にコンポーネントを更新するには [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) を実行してください。 @@ -388,9 +388,9 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co -This API has been renamed from `componentWillReceiveProps` to [`UNSAFE_componentWillReceiveProps`.](#unsafe_componentwillreceiveprops) The old name has been deprecated. In a future major version of React, only the new name will work. +この API は `componentWillReceiveProps` から [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops) に名前が変更されました。古い名前は非推奨となりました。React の将来のメジャーバージョンでは、新しい名前のみが機能します。 -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +自動的にコンポーネントを更新するには [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) を実行してください。 @@ -400,9 +400,9 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co -This API has been renamed from `componentWillUpdate` to [`UNSAFE_componentWillUpdate`.](#unsafe_componentwillupdate) The old name has been deprecated. In a future major version of React, only the new name will work. +この API は `componentWillUpdate` から [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate) に名前が変更されました。古い名前は非推奨となりました。React の将来のメジャーバージョンでは、新しい名前のみが機能します。 -Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) to automatically update your components. +自動的にコンポーネントを更新するには [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) を実行してください。 @@ -410,9 +410,9 @@ Run the [`rename-unsafe-lifecycles` codemod](https://github.com/reactjs/react-co ### `componentWillUnmount()` {/*componentwillunmount*/} -If you define the `componentWillUnmount` method, React will call it before your component is removed *(unmounted)* from the screen. This is a common place to cancel data fetching or remove subscriptions. +`componentWillUnmount` メソッドを定義すると、React はコンポーネントが画面から削除(アンマウント)される前にこれを呼び出します。ここがデータの取得をキャンセルしたり、サブスクリプションを削除するのに一般的な場所です。 -The logic inside `componentWillUnmount` should "mirror" the logic inside [`componentDidMount`.](#componentdidmount) For example, if `componentDidMount` sets up a subscription, `componentWillUnmount` should clean up that subscription. If the cleanup logic in your `componentWillUnmount` reads some props or state, you will usually also need to implement [`componentDidUpdate`](#componentdidupdate) to clean up resources (such as subscriptions) corresponding to the old props and state. +`componentWillUnmount` 内のロジックは [`componentDidMount`](#componentdidmount) 内のロジックと「鏡のように対応」するべきです。例えば、`componentDidMount` がサブスクリプションの設定を行う場合、`componentWillUnmount` はそのサブスクリプションをクリーンアップするべきです。`componentWillUnmount` のクリーンアップロジックが props や state を読み取る場合、通常は古い props と state に対応するリソース(サブスクリプションなど)をクリーンアップするために [`componentDidUpdate`](#componentdidupdate) も実装する必要があります。 ```js {20-22} class ChatRoom extends Component { @@ -442,25 +442,25 @@ class ChatRoom extends Component { } ``` -[See more examples.](#adding-lifecycle-methods-to-a-class-component) +[他の例を見る](#adding-lifecycle-methods-to-a-class-component) -#### Parameters {/*componentwillunmount-parameters*/} +#### 引数 {/*componentwillunmount-parameters*/} -`componentWillUnmount` does not take any parameters. +`componentWillUnmount` は引数を受け取りません。 -#### Returns {/*componentwillunmount-returns*/} +#### 返り値 {/*componentwillunmount-returns*/} -`componentWillUnmount` should not return anything. +`componentWillUnmount` は何も返してはいけません。 -#### Caveats {/*componentwillunmount-caveats*/} +#### 注意点 {/*componentwillunmount-caveats*/} -- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call [`componentDidMount`,](#componentdidmount) then immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does. +- [Strict Mode](/reference/react/StrictMode) がオンの場合、React は開発中に [`componentDidMount`](#componentdidmount) を呼び出し、直後に `componentWillUnmount` を呼び出し、そして再度 `componentDidMount` を呼び出します。これにより、`componentWillUnmount` の実装を忘れた場合や、そのロジックが `componentDidMount` の挙動と正しく「鏡のように対応」していない場合に気づきやすくなります。 -For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match. +多くのユースケースにおいて、クラスコンポーネントで `componentDidMount`、`componentDidUpdate`、`componentWillUnmount` をまとめて定義することは、関数コンポーネントで [`useEffect`](/reference/react/useEffect) を呼び出すことと同等です。ブラウザの描画前にコードを実行することが重要となる稀なケースでは、[`useLayoutEffect`](/reference/react/useLayoutEffect) がより近いものになります。 -[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) @@ -468,27 +468,27 @@ For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `com ### `forceUpdate(callback?)` {/*forceupdate*/} -Forces a component to re-render. +コンポーネントを強制的に再レンダーします。 -Usually, this is not necessary. If your component's [`render`](#render) method only reads from [`this.props`](#props), [`this.state`](#state), or [`this.context`,](#context) it will re-render automatically when you call [`setState`](#setstate) inside your component or one of its parents. However, if your component's `render` method reads directly from an external data source, you have to tell React to update the user interface when that data source changes. That's what `forceUpdate` lets you do. +通常、これは必要ありません。コンポーネントの [`render`](#render) メソッドが [`this.props`](#props)、[`this.state`](#state) および [`this.context`](#context) からのみ読み取りを行う場合、コンポーネント内またはその親で [`setState`](#setstate) が呼び出されると自動的に再レンダーが発生します。しかし、コンポーネントの `render` メソッドが外部データソースから直接読み取りを行っている場合、そのデータソースが変更されたときに React にユーザインターフェースを更新するように指示する必要があります。`forceUpdate` はそれを行えるようにするためのものです。 -Try to avoid all uses of `forceUpdate` and only read from `this.props` and `this.state` in `render`. +あらゆる `forceUpdate` の使用は避け、`render` 内では `this.props` と `this.state` からのみ読み取るようにしてください。 -#### Parameters {/*forceupdate-parameters*/} +#### 引数 {/*forceupdate-parameters*/} -* **optional** `callback` If specified, React will call the `callback` you've provided after the update is committed. +* **省略可能** `callback`: 指定された場合、React は更新がコミットされた後に、渡された `callback` を呼び出します。 -#### Returns {/*forceupdate-returns*/} +#### 返り値 {/*forceupdate-returns*/} -`forceUpdate` does not return anything. +`forceUpdate` は何も返しません。 -#### Caveats {/*forceupdate-caveats*/} +#### 注意点 {/*forceupdate-caveats*/} -- If you call `forceUpdate`, React will re-render without calling [`shouldComponentUpdate`.](#shouldcomponentupdate) +- `forceUpdate` を呼び出すと、React は [`shouldComponentUpdate`](#shouldcomponentupdate) を呼び出さずに再レンダーします。 -Reading an external data source and forcing class components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/reference/react/useSyncExternalStore) in function components. +外部データソースを読み込んで変更に応じて `forceUpdate` でクラスコンポーネントを再レンダーする代わりに、関数コンポーネントにおいては [`useSyncExternalStore`](/reference/react/useSyncExternalStore) を使うようになりました。 @@ -498,19 +498,19 @@ Reading an external data source and forcing class components to re-render in res -This API will be removed in a future major version of React. [Use `Context.Provider` instead.](/reference/react/createContext#provider) +この API は、React の将来のメジャーバージョンで削除されます。代わりに [`Context.Provider` を使用してください](/reference/react/createContext#provider)。 -Lets you specify the values for the [legacy context](https://reactjs.org/docs/legacy-context.html) is provided by this component. +このコンポーネントが提供する[レガシーコンテクスト](https://reactjs.org/docs/legacy-context.html)の値を指定します。 --- ### `getSnapshotBeforeUpdate(prevProps, prevState)` {/*getsnapshotbeforeupdate*/} -If you implement `getSnapshotBeforeUpdate`, React will call it immediately before React updates the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to [`componentDidUpdate`.](#componentdidupdate) +`getSnapshotBeforeUpdate` を実装すると、React は DOM を更新する直前にそれを呼び出します。これにより、コンポーネントは DOM から情報(例えばスクロール位置)を取得することができます。このライフサイクルメソッドが返すあらゆる値は、[`componentDidUpdate`](#componentdidupdate) に引数として渡されます。 -For example, you can use it in a UI like a chat thread that needs to preserve its scroll position during updates: +例えば、更新間でスクロール位置を保持する必要があるチャットスレッドのような UI でこれを使用することができます。 ```js {7-15,17} class ScrollingList extends React.Component { @@ -547,25 +547,25 @@ class ScrollingList extends React.Component { } ``` -In the above example, it is important to read the `scrollHeight` property directly in `getSnapshotBeforeUpdate`. It is not safe to read it in [`render`](#render), [`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops), or [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate) because there is a potential time gap between these methods getting called and React updating the DOM. +上記の例では、`getSnapshotBeforeUpdate` で直接 `scrollHeight` プロパティを読み取ることが重要です。[`render`](#render)、[`UNSAFE_componentWillReceiveProps`](#unsafe_componentwillreceiveprops)、または [`UNSAFE_componentWillUpdate`](#unsafe_componentwillupdate) で読み取ることは安全ではありません。これらのメソッドが呼び出されてから React が DOM を更新するまでに時間差がある可能性があるためです。 -#### Parameters {/*getsnapshotbeforeupdate-parameters*/} +#### 引数 {/*getsnapshotbeforeupdate-parameters*/} -* `prevProps`: Props before the update. Compare `prevProps` to [`this.props`](#props) to determine what changed. +* `prevProps`: 更新前の props。`prevProps` と [`this.props`](#props) を比較して何が変わったかを判断します。 -* `prevState`: State before the update. Compare `prevState` to [`this.state`](#state) to determine what changed. +* `prevState`: 更新前の state。`prevState` と [`this.state`](#state) を比較して何が変わったかを判断します。 -#### Returns {/*getsnapshotbeforeupdate-returns*/} +#### 返り値 {/*getsnapshotbeforeupdate-returns*/} -You should return a snapshot value of any type that you'd like, or `null`. The value you returned will be passed as the third argument to [`componentDidUpdate`.](#componentdidupdate) +任意の型のスナップショット値、または `null` を返してください。返した値は、[`componentDidUpdate`](#componentdidupdate) の第 3 引数として渡されます。 -#### Caveats {/*getsnapshotbeforeupdate-caveats*/} +#### 注意点 {/*getsnapshotbeforeupdate-caveats*/} -- `getSnapshotBeforeUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- [`shouldComponentUpdate`](#shouldcomponentupdate) が定義されており、`false` を返す場合、`getSnapshotBeforeUpdate` は呼び出されません。 -At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function components. This use case is very uncommon, but if you have the need for it, for now you'll have to write a class component. +現時点では、関数コンポーネントには `getSnapshotBeforeUpdate` と同等のものはありません。このユースケースは非常に珍しいものですが、これがどうしても必要な場合、現時点ではクラスコンポーネントを書く必要があります。 @@ -573,9 +573,9 @@ At the moment, there is no equivalent to `getSnapshotBeforeUpdate` for function ### `render()` {/*render*/} -The `render` method is the only required method in a class component. +`render` メソッドは、クラスコンポーネントにおける唯一の必須メソッドです。 -The `render` method should specify what you want to appear on the screen, for example: +`render` メソッドは、画面に表示したいものを指定します。例えば: ```js {4-6} import { Component } from 'react'; @@ -587,33 +587,33 @@ class Greeting extends Component { } ``` -React may call `render` at any moment, so you shouldn't assume that it runs at a particular time. Usually, the `render` method should return a piece of [JSX](/learn/writing-markup-with-jsx), but a few [other return types](#render-returns) (like strings) are supported. To calculate the returned JSX, the `render` method can read [`this.props`](#props), [`this.state`](#state), and [`this.context`](#context). +React はあらゆるタイミングで `render` を呼び出す可能性があるため、特定の時間に実行されることを前提にしてはいけません。通常、`render` メソッドは [JSX](/learn/writing-markup-with-jsx) を返すべきですが、いくつかの[他の型の返り値](#render-returns)(文字列など)もサポートされています。返すべき JSX を計算するために、`render` メソッドは [`this.props`](#props)、[`this.state`](#state)、および [`this.context`](#context) を読み取ることができます。 -You should write the `render` method as a pure function, meaning that it should return the same result if props, state, and context are the same. It also shouldn't contain side effects (like setting up subscriptions) or interact with the browser APIs. Side effects should happen either in event handlers or methods like [`componentDidMount`.](#componentdidmount) +`render` メソッドは純関数として書くべきです。つまり、props、state、コンテクストが同じであれば同じ結果を返すべきです。また、副作用(サブスクリプションの設定など)を含んだり、ブラウザの API とやり取りしたりするべきではありません。副作用は、イベントハンドラや [`componentDidMount`](#componentdidmount) のようなメソッド内で行うべきです。 -#### Parameters {/*render-parameters*/} +#### 引数 {/*render-parameters*/} -`render` does not take any parameters. +`render` は引数を受け取りません。 -#### Returns {/*render-returns*/} +#### 返り値 {/*render-returns*/} -`render` can return any valid React node. This includes React elements such as `
`, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. +`render` はあらゆる有効な React ノードを返すことができます。これには、`
` のような React 要素、文字列、数値、[ポータル](/reference/react-dom/createPortal)、空のノード(`null`、`undefined`、`true`、`false`)、および React ノードの配列が含まれます。 -#### Caveats {/*render-caveats*/} +#### 注意点 {/*render-caveats*/} -- `render` should be written as a pure function of props, state, and context. It should not have side effects. +- `render` は props、state、コンテクストに対する純関数として書くべきです。副作用を持ってはいけません。 -- `render` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- [`shouldComponentUpdate`](#shouldcomponentupdate) が定義されており `false` を返す場合、`render` は呼び出されません。 -- When [Strict Mode](/reference/react/StrictMode) is on, React will call `render` twice in development and then throw away one of the results. This helps you notice the accidental side effects that need to be moved out of the `render` method. +- [Strict Mode](/reference/react/StrictMode) が有効の場合、React は開発中に `render` を 2 回呼び出し、そのうちの 1 つの結果を破棄します。これにより、`render` メソッドの外に移動するべき偶発的な副作用に気づきやすくなります。 -- There is no one-to-one correspondence between the `render` call and the subsequent `componentDidMount` or `componentDidUpdate` call. Some of the `render` call results may be discarded by React when it's beneficial. +- `render` の呼び出しとその後の `componentDidMount` や `componentDidUpdate` の呼び出しとの間に一対一の対応関係はありません。React が必要と判断した場合、`render` の呼び出し結果の一部は破棄される可能性があります。 --- ### `setState(nextState, callback?)` {/*setstate*/} -Call `setState` to update the state of your React component. +`setState` の呼び出しは React コンポーネントの state の更新を行います。 ```js {8-10} class Form extends Component { @@ -639,11 +639,11 @@ class Form extends Component { } ``` -`setState` enqueues changes to the component state. It tells React that this component and its children need to re-render with the new state. This is the main way you'll update the user interface in response to interactions. +`setState` はコンポーネントの state への更新をキューに入れます。これは、このコンポーネントとその子を新しい state で再レンダーする必要があることを React に伝えます。これが、ユーザ操作に対応してユーザインターフェースを更新するための主要な方法となります。 -Calling `setState` **does not** change the current state in the already executing code: +`setState` を呼び出しても、すでに実行中のコードの現在の state は**変更されません**。 ```js {6} function handleClick() { @@ -655,11 +655,11 @@ function handleClick() { } ``` -It only affects what `this.state` will return starting from the *next* render. +これは、*次回の*レンダーから `this.state` が返すものにのみ影響します。 -You can also pass a function to `setState`. It lets you update state based on the previous state: +また、`setState` に関数を渡すこともできます。これにより、前の state に基づいて state を更新することができます。 ```js {2-6} handleIncreaseAge = () => { @@ -671,31 +671,31 @@ You can also pass a function to `setState`. It lets you update state based on th } ``` -You don't have to do this, but it's handy if you want to update state multiple times during the same event. +こうする必要があるわけではありませんが、同じイベント中に複数回 state を更新したい場合には有用です。 -#### Parameters {/*setstate-parameters*/} +#### 引数 {/*setstate-parameters*/} -* `nextState`: Either an object or a function. - * If you pass an object as `nextState`, it will be shallowly merged into `this.state`. - * If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state and props as arguments, and should return the object to be shallowly merged into `this.state`. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. +* `nextState`:オブジェクトまたは関数。 + * `nextState` としてオブジェクトを渡すと、それは `this.state` に浅く (shallow) マージされます。 + * `nextState` として関数を渡すと、それは*更新用関数 (updater function)* として扱われます。その関数は純関数でなければならず、state と props の現在値を引数として取り、`this.state` に浅くマージされるためのオブジェクトを返します。React はこの更新用関数をキューに入れてからコンポーネントを再レンダーします。次のレンダー中に、React は前の state に対してキューに入れられたすべての更新用関数を適用し、次回の state を計算します。 -* **optional** `callback`: If specified, React will call the `callback` you've provided after the update is committed. +* **省略可能** `callback`: 指定された場合、React は更新がコミットされた後に渡された `callback` を呼び出します。 -#### Returns {/*setstate-returns*/} +#### 返り値 {/*setstate-returns*/} -`setState` does not return anything. +`setState` は何も返しません。 -#### Caveats {/*setstate-caveats*/} +#### 注意点 {/*setstate-caveats*/} -- Think of `setState` as a *request* rather than an immediate command to update the component. When multiple components update their state in response to an event, React will batch their updates and re-render them together in a single pass at the end of the event. In the rare case that you need to force a particular state update to be applied synchronously, you may wrap it in [`flushSync`,](/reference/react-dom/flushSync) but this may hurt performance. +- `setState` は即時的なコンポーネントの更新命令ではなく、*リクエスト*だと考えてください。複数のコンポーネントがイベントに応じて state を更新するとき、React はそれらの更新をバッチ(束ね)処理し、イベントの終了時に 1 度だけ再レンダーします。特定の state 更新を強制的に同期的に適用する必要がある稀なケースでは、[`flushSync`](/reference/react-dom/flushSync) でラップすることができますが、これはパフォーマンスを低下させる可能性があります。 -- `setState` does not update `this.state` immediately. This makes reading `this.state` right after calling `setState` a potential pitfall. Instead, use [`componentDidUpdate`](#componentdidupdate) or the setState `callback` argument, either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, you can pass a function to `nextState` as described above. +- `setState` は `this.state` を即時に更新しません。このため、`setState` を呼び出した直後に `this.state` を読み取ることは潜在的な落とし穴となります。代わりに、[`componentDidUpdate`](#componentdidupdate) または setState の `callback` 引数を使用してください。どちらも更新が適用された後に発火することが保証されています。前の state に基づいた state を設定する必要がある場合、上記で説明したように `nextState` として関数を渡すことができます。 -Calling `setState` in class components is similar to calling a [`set` function](/reference/react/useState#setstate) in function components. +クラスコンポーネントで `setState` を呼び出すことは、関数コンポーネントで [`set` 関数](/reference/react/useState#setstate)を呼び出すことに似ています。 -[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-state-from-a-class-to-a-function) @@ -703,9 +703,9 @@ Calling `setState` in class components is similar to calling a [`set` function]( ### `shouldComponentUpdate(nextProps, nextState, nextContext)` {/*shouldcomponentupdate*/} -If you define `shouldComponentUpdate`, React will call it to determine whether a re-render can be skipped. +`shouldComponentUpdate` を定義すると、React は再レンダーをスキップできるかどうかを判断するためにそれを呼び出します。 -If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped. +これを本当に手動で書きたい場合は、`this.props` と `nextProps`、`this.state` と `nextState` を比較した上で `false` を返すことで、更新をスキップできると React に伝えることができます。 ```js {6-18} class Rectangle extends Component { @@ -732,35 +732,35 @@ class Rectangle extends Component { ``` -React calls `shouldComponentUpdate` before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when [`forceUpdate`](#forceupdate) is used. +新しい props や state を受け取る際に React は `shouldComponentUpdate` を呼び出します。デフォルトは `true` です。このメソッドは初回レンダーの場合と [`forceUpdate`](#forceupdate) が使用された場合には呼び出されません。 -#### Parameters {/*shouldcomponentupdate-parameters*/} +#### 引数 {/*shouldcomponentupdate-parameters*/} -- `nextProps`: The next props that the component is about to render with. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextState`: The next state that the component is about to render with. Compare `nextState` to [`this.state`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to render with. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype) (modern) or [`static contextTypes`](#static-contexttypes) (legacy). +- `nextProps`: コンポーネントがレンダーしようとしている次の props。何が変わったかを判断するために `nextProps` を [`this.props`](#props) と比較します。 +- `nextState`: コンポーネントがレンダーしようとしている次の state。何が変わったかを判断するために `nextState` を [`this.state`](#props) と比較します。 +- `nextContext`: コンポーネントがレンダーしようとしている次のコンテクスト。何が変わったかを判断するために `nextContext` を [`this.context`](#context) と比較します。[`static contextType`](#static-contexttype)(現行版)または [`static contextTypes`](#static-contexttypes)(レガシー)を指定した場合のみ利用可能です。 -#### Returns {/*shouldcomponentupdate-returns*/} +#### 返り値 {/*shouldcomponentupdate-returns*/} -Return `true` if you want the component to re-render. That's the default behavior. +コンポーネントを再レンダーしたい場合は `true` を返します。これがデフォルトの挙動です。 -Return `false` to tell React that re-rendering can be skipped. +再レンダーがスキップ可能であると React に伝えるためには `false` を返します。 -#### Caveats {/*shouldcomponentupdate-caveats*/} +#### 注意点 {/*shouldcomponentupdate-caveats*/} -- This method *only* exists as a performance optimization. If your component breaks without it, fix that first. +- このメソッドは*パフォーマンス最適化のためだけ*に存在しています。もし、このメソッドがないとコンポーネントが壊れる場合は、まずそれを修正してください。 -- Consider using [`PureComponent`](/reference/react/PureComponent) instead of writing `shouldComponentUpdate` by hand. `PureComponent` shallowly compares props and state, and reduces the chance that you'll skip a necessary update. +- `shouldComponentUpdate` を手書きする代わりに、[`PureComponent`](/reference/react/PureComponent) の使用を検討してください。`PureComponent` は props と state を浅く比較し、必要な更新までスキップしてしまう可能性を減らします。 -- We do not recommend doing deep equality checks or using `JSON.stringify` in `shouldComponentUpdate`. It makes performance unpredictable and dependent on the data structure of every prop and state. In the best case, you risk introducing multi-second stalls to your application, and in the worst case you risk crashing it. +- `shouldComponentUpdate` で深い等価性チェックを行ったり、`JSON.stringify` を使用したりすることはお勧めしません。これによりパフォーマンスがあらゆる props と state のデータ構造に依存するようになり、予測不可能になります。よくてもアプリケーションが数秒間フリーズするリスクがあり、最悪の場合はクラッシュする危険があります。 -- Returning `false` does not prevent child components from re-rendering when *their* state changes. +- `false` を返しても、*子コンポーネントの* state が変更された場合に子コンポーネントの再レンダーが抑止されるわけではありません。 -- Returning `false` does not *guarantee* that the component will not re-render. React will use the return value as a hint but it may still choose to re-render your component if it makes sense to do for other reasons. +- `false` を返しても、コンポーネントが再レンダーされないことが*保証*されるわけではありません。React は返り値をヒントとして使用しますが、他の理由でコンポーネントを再レンダーすることが理にかなっていると判断した場合、再レンダーを行うことがあります。 -Optimizing class components with `shouldComponentUpdate` is similar to optimizing function components with [`memo`.](/reference/react/memo) Function components also offer more granular optimization with [`useMemo`.](/reference/react/useMemo) +クラスコンポーネントを `shouldComponentUpdate` で最適化することは、関数コンポーネントを [`memo` で最適化すること](/reference/react/memo)と似ています。関数コンポーネントでは [`useMemo`](/reference/react/useMemo) を使用することで、さらに細かい最適化も行えます。 @@ -768,32 +768,32 @@ Optimizing class components with `shouldComponentUpdate` is similar to optimizin ### `UNSAFE_componentWillMount()` {/*unsafe_componentwillmount*/} -If you define `UNSAFE_componentWillMount`, React will call it immediately after the [`constructor`.](#constructor) It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +`UNSAFE_componentWillMount` を定義すると、React は [`constructor` の直後に](#constructor)それを呼び出します。これは歴史的な理由で存在するものであり、新しいコードでは使用すべきではありません。代わりに以下の代替手段のいずれかを使用してください。 -- To initialize state, declare [`state`](#state) as a class field or set `this.state` inside the [`constructor`.](#constructor) -- If you need to run a side effect or set up a subscription, move that logic to [`componentDidMount`](#componentdidmount) instead. +- state を初期化するためには、[`state` をクラスフィールドとして宣言する](#state)か、[`constructor`](#constructor) で `this.state` を設定します。 +- 副作用を実行する必要があるか、サブスクリプションを設定する必要がある場合は、そのロジックを [`componentDidMount`](#componentdidmount) に移動します。 -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) +[安全でないライフサイクルからの移行例を見る](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) -#### Parameters {/*unsafe_componentwillmount-parameters*/} +#### 引数 {/*unsafe_componentwillmount-parameters*/} -`UNSAFE_componentWillMount` does not take any parameters. +`UNSAFE_componentWillMount` は引数を受け取りません。 -#### Returns {/*unsafe_componentwillmount-returns*/} +#### 返り値 {/*unsafe_componentwillmount-returns*/} -`UNSAFE_componentWillMount` should not return anything. +`UNSAFE_componentWillMount` は何も返してはいけません。 -#### Caveats {/*unsafe_componentwillmount-caveats*/} +#### 注意点 {/*unsafe_componentwillmount-caveats*/} -- `UNSAFE_componentWillMount` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- コンポーネントが [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) または [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) を実装している場合、`UNSAFE_componentWillMount` は呼び出されません。 -- Despite its naming, `UNSAFE_componentWillMount` does not guarantee that the component *will* get mounted if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. This is why this method is "unsafe". Code that relies on mounting (like adding a subscription) should go into [`componentDidMount`.](#componentdidmount) +- [`Suspense`](/reference/react/Suspense) のようなモダンな React 機能を使用しているアプリでは、`UNSAFE_componentWillMount` はその名前に反して、コンポーネントが*本当にマウント*されることを保証しません。(例えば子コンポーネントのコードがまだロードされていないなどの理由で)レンダーの試行がサスペンドした場合、React は進行中のツリーを破棄し、次の試行にてコンポーネントをゼロから構築しようとします。これがこのメソッドが "unsafe" となっている理由です。実際にマウントされたという事実に依存するコード(サブスクリプションの追加など)は [`componentDidMount`](#componentdidmount) に入れるべきです。 -- `UNSAFE_componentWillMount` is the only lifecycle method that runs during [server rendering.](/reference/react-dom/server) For all practical purposes, it is identical to [`constructor`,](#constructor) so you should use the `constructor` for this type of logic instead. +- `UNSAFE_componentWillMount` は[サーバレンダリング](/reference/react-dom/server)中に実行される唯一のライフサイクルメソッドです。現実的にはあらゆる利用目的においてこれは [`constructor`](#constructor) と同一であるため、このタイプのロジックには `constructor` を使用すべきです。 -Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class component to initialize state is equivalent to passing that state as the initial state to [`useState`](/reference/react/useState) in a function component. +クラスコンポーネントの `UNSAFE_componentWillMount` 内で state を初期化するために [`setState`](#setstate) を呼び出すことは、関数コンポーネントの [`useState`](/reference/react/useState) に初期 state を渡すことと同等です。 @@ -801,37 +801,37 @@ Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class co ### `UNSAFE_componentWillReceiveProps(nextProps, nextContext)` {/*unsafe_componentwillreceiveprops*/} -If you define `UNSAFE_componentWillReceiveProps`, React will call it when the component receives new props. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +`UNSAFE_componentWillReceiveProps` を定義すると、コンポーネントが新しい props を受け取るときに React がそれを呼び出します。これは歴史的な理由で存在するものであり、新しいコードでは使用すべきではありません。代わりに以下の代替手段のいずれかを使用してください。 -- If you need to **run a side effect** (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop changes, move that logic to [`componentDidUpdate`](#componentdidupdate) instead. -- If you need to **avoid re-computing some data only when a prop changes,** use a [memoization helper](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization) instead. -- If you need to **"reset" some state when a prop changes,** consider either making a component [fully controlled](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a key](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead. -- If you need to **"adjust" some state when a prop changes,** check whether you can compute all the necessary information from props alone during rendering. If you can't, use [`static getDerivedStateFromProps`](/reference/react/Component#static-getderivedstatefromprops) instead. +- props の変更に応じて**副作用を実行**する必要がある場合(例えば、データの取得、アニメーションの実行、またはサブスクリプションの再初期化)、そのロジックを代わりに [`componentDidUpdate`](#componentdidupdate) に移動してください。 +- 一部の props が変更されたときに**あるデータの再計算を避ける**必要がある場合、代わりに[メモ化ヘルパー](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization)を使用してください。 +- props が変更されたときに**ある state を「リセット」する**必要がある場合、コンポーネントを[完全に制御されたコンポーネント](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component)にするか、[key 付きの非制御コンポーネント](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key)にすることを検討してください。 +- props が変更されたときに**ある state を「調整」する**必要がある場合、レンダー中に props のみから必要な情報をすべて計算できないか確認してください。できない場合は、代わりに [`static getDerivedStateFromProps`](/reference/react/Component#static-getderivedstatefromprops) を使用してください。 -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props) +[安全でないライフサイクルからの移行の例を見る](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props) -#### Parameters {/*unsafe_componentwillreceiveprops-parameters*/} +#### 引数 {/*unsafe_componentwillreceiveprops-parameters*/} -- `nextProps`: The next props that the component is about to receive from its parent component. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextContext`: The next context that the component is about to receive from the closest provider. Compare `nextContext` to [`this.context`](#context) to determine what changed. Only available if you specify [`static contextType`](#static-contexttype) (modern) or [`static contextTypes`](#static-contexttypes) (legacy). +- `nextProps`: コンポーネントが親コンポーネントから受け取ろうとしている次の props。何が変更されたかを判断するために `nextProps` を [`this.props`](#props) と比較します。 +- `nextContext`: コンポーネントが最も近いプロバイダから受け取ろうとしている次のコンテクスト。何が変更されたかを判断するために `nextContext` を [`this.context`](#context) と比較します。[`static contextType`](#static-contexttype)(現行版)または [`static contextTypes`](#static-contexttypes)(レガシー)を指定した場合のみ利用可能です。 -#### Returns {/*unsafe_componentwillreceiveprops-returns*/} +#### 返り値 {/*unsafe_componentwillreceiveprops-returns*/} -`UNSAFE_componentWillReceiveProps` should not return anything. +`UNSAFE_componentWillReceiveProps` は何も返してはいけません。 -#### Caveats {/*unsafe_componentwillreceiveprops-caveats*/} +#### 注意点 {/*unsafe_componentwillreceiveprops-caveats*/} -- `UNSAFE_componentWillReceiveProps` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) または [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) を実装しているコンポーネントでは、`UNSAFE_componentWillReceiveProps` は呼び出されません。 -- Despite its naming, `UNSAFE_componentWillReceiveProps` does not guarantee that the component *will* receive those props if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate) +- [`Suspense`](/reference/react/Suspense) のようなモダンな React 機能を使用しているアプリでは、`UNSAFE_componentWillReceiveProps` はその名前に反して、コンポーネントがその props を*本当に受け取る*ことを保証しません。(例えば子コンポーネントのコードがまだロードされていないなどの理由で)レンダーの試行がサスペンドした場合、React は進行中のツリーを破棄し、次の試行にてコンポーネントをゼロから構築しようとします。次のレンダーの試行の時点では、props は異なっている可能性があります。これがこのメソッドが "unsafe" となっている理由です。コミットされた更新のみに対して実行すべきコード(サブスクリプションのリセットなど)は、[`componentDidUpdate`](#componentdidupdate) に入れるべきです。 -- `UNSAFE_componentWillReceiveProps` does not mean that the component has received *different* props than the last time. You need to compare `nextProps` and `this.props` yourself to check if something changed. +- `UNSAFE_componentWillReceiveProps` が呼ばれてもコンポーネントが前回と*異なる* props を受け取ったことを意味するものではありません。何かが変わったかどうかを確認するには `nextProps` と `this.props` を自分で比較する必要があります。 -- React doesn't call `UNSAFE_componentWillReceiveProps` with initial props during mounting. It only calls this method if some of component's props are going to be updated. For example, calling [`setState`](#setstate) doesn't generally trigger `UNSAFE_componentWillReceiveProps` inside the same component. +- React はマウント時に `UNSAFE_componentWillReceiveProps` を初期 props を引数に呼び出すことはありません。このメソッドは、コンポーネントの props の一部が更新される予定の場合にのみ呼び出されます。例えば、[`setState`](#setstate) を呼び出しても、一般的には同じコンポーネント内の `UNSAFE_componentWillReceiveProps` はトリガされません。 -Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a class component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component. +クラスコンポーネントで `UNSAFE_componentWillReceiveProps` 内部で [`setState`](#setstate) を呼び出して state を「調整」することは、関数コンポーネントで[レンダー中に `useState` の `set` 関数を呼び出す](/reference/react/useState#storing-information-from-previous-renders) ことと同等です。 @@ -840,39 +840,39 @@ Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a c ### `UNSAFE_componentWillUpdate(nextProps, nextState)` {/*unsafe_componentwillupdate*/} -If you define `UNSAFE_componentWillUpdate`, React will call it before rendering with the new props or state. It only exists for historical reasons and should not be used in any new code. Instead, use one of the alternatives: +`UNSAFE_componentWillUpdate` を定義すると、新しい props または state でレンダーする前に React がそれを呼び出します。これは歴史的な理由で存在するものであり、新しいコードでは使用すべきではありません。代わりに以下の代替手段のいずれかを使用してください。 -- If you need to run a side effect (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop or state changes, move that logic to [`componentDidUpdate`](#componentdidupdate) instead. -- If you need to read some information from the DOM (for example, to save the current scroll position) so that you can use it in [`componentDidUpdate`](#componentdidupdate) later, read it inside [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) instead. +- prop または state の変更に応じて副作用(例えば、データの取得、アニメーションの実行、サブスクリプションの再初期化など)を実行する必要がある場合、そのロジックを [`componentDidUpdate`](#componentdidupdate) に移動してください。 +- DOM から情報を読み取り(例えば、現在のスクロール位置を保存するなど)、それを後で [`componentDidUpdate`](#componentdidupdate) で使用する場合は、[`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) 内で読み取るようにしてください。 -[See examples of migrating away from unsafe lifecycles.](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) +[安全でないライフサイクルからの移行例を見る](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#examples) -#### Parameters {/*unsafe_componentwillupdate-parameters*/} +#### 引数 {/*unsafe_componentwillupdate-parameters*/} -- `nextProps`: The next props that the component is about to render with. Compare `nextProps` to [`this.props`](#props) to determine what changed. -- `nextState`: The next state that the component is about to render with. Compare `nextState` to [`this.state`](#state) to determine what changed. +- `nextProps`: コンポーネントが次にレンダーする予定の props。何が変わったかを判断するために、`nextProps` と [`this.props`](#props) を比較します。 +- `nextState`: コンポーネントが次にレンダーする予定の state。何が変わったかを判断するために、`nextState` と [`this.state`](#state) を比較します。 -#### Returns {/*unsafe_componentwillupdate-returns*/} +#### 返り値 {/*unsafe_componentwillupdate-returns*/} -`UNSAFE_componentWillUpdate` should not return anything. +`UNSAFE_componentWillUpdate` は何も返してはいけません。 -#### Caveats {/*unsafe_componentwillupdate-caveats*/} +#### 注意点 {/*unsafe_componentwillupdate-caveats*/} -- `UNSAFE_componentWillUpdate` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`. +- [`shouldComponentUpdate`](#shouldcomponentupdate) が定義されており `false` を返す場合、`UNSAFE_componentWillUpdate` は呼び出されません。 -- `UNSAFE_componentWillUpdate` will not get called if the component implements [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate) +- コンポーネントが [`static getDerivedStateFromProps`](#static-getderivedstatefromprops) または [`getSnapshotBeforeUpdate`](#getsnapshotbeforeupdate) を実装している場合、`UNSAFE_componentWillUpdate` は呼び出されません。 -- It's not supported to call [`setState`](#setstate) (or any method that leads to `setState` being called, like dispatching a Redux action) during `componentWillUpdate`. +- `componentWillUpdate` の呼び出し中に [`setState`](#setstate)(または最終的に `setState` が呼び出されるようなあらゆるメソッド、例えば Redux アクションのディスパッチ)を呼び出すことはサポートされていません。 -- Despite its naming, `UNSAFE_componentWillUpdate` does not guarantee that the component *will* update if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props and state might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate) +- [`Suspense`](/reference/react/Suspense) のようなモダンな React 機能を使用しているアプリでは、`UNSAFE_componentWillUpdate` はその名前に反して、コンポーネントが*本当に更新される*ことを保証しません。(例えば子コンポーネントのコードがまだロードされていないなどの理由で)レンダーの試行がサスペンドした場合、React は進行中のツリーを破棄し、次の試行にてコンポーネントをゼロから構築しようとします。次のレンダーの試行の時点では props と state は異なっている可能性があります。これがこのメソッドが "unsafe" となっている理由です。コミットされた更新のみに対して実行すべきコード(サブスクリプションのリセットなど)は、[`componentDidUpdate`](#componentdidupdate) に入れるべきです。 -- `UNSAFE_componentWillUpdate` does not mean that the component has received *different* props or state than the last time. You need to compare `nextProps` with `this.props` and `nextState` with `this.state` yourself to check if something changed. +- `UNSAFE_componentWillUpdate` が呼ばれてもコンポーネントが前回とは*異なる* props や state を受け取ったことを意味するものではありません。何かが変わったかどうかを確認するには、`nextProps` と `this.props`、`nextState` と `this.state` を自分で比較する必要があります。 -- React doesn't call `UNSAFE_componentWillUpdate` with initial props and state during mounting. +- React は props や state の初期値を使ってマウント時に `UNSAFE_componentWillUpdate` を呼び出すことはしません。 -There is no direct equivalent to `UNSAFE_componentWillUpdate` in function components. +関数コンポーネントには `UNSAFE_componentWillUpdate` に直接対応するものはありません。 @@ -882,11 +882,11 @@ There is no direct equivalent to `UNSAFE_componentWillUpdate` in function compon -This API will be removed in a future major version of React. [Use `static contextType` instead.](#static-contexttype) +この API は React の将来のメジャーバージョンで削除されます。代わりに [`static contextType`](#static-contexttype) を使用してください。 -Lets you specify which [legacy context](https://reactjs.org/docs/legacy-context.html) is provided by this component. +このコンポーネントによって提供される[レガシーコンテクスト](https://reactjs.org/docs/legacy-context.html)を指定します。 --- @@ -894,17 +894,17 @@ Lets you specify which [legacy context](https://reactjs.org/docs/legacy-context. -This API will be removed in a future major version of React. [Use `static contextType` instead.](#static-contexttype) +この API は React の将来のメジャーバージョンで削除されます。代わりに [`static contextType`](#static-contexttype) を使用してください。 -Lets you specify which [legacy context](https://reactjs.org/docs/legacy-context.html) is consumed by this component. +このコンポーネントが使用する[レガシーコンテクスト](https://reactjs.org/docs/legacy-context.html)を指定します。 --- ### `static contextType` {/*static-contexttype*/} -If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which context it needs to read. The context you specify as the `static contextType` must be a value previously created by [`createContext`.](/reference/react/createContext) +クラスコンポーネントで [`this.context`](#context-instance-field) を読み取りたい場合、読み取りたいコンテクストをこれで指定する必要があります。`static contextType` として指定するコンテクストは、以前に [`createContext`](/reference/react/createContext) で作成されている値でなければなりません。 ```js {2} class Button extends Component { @@ -924,9 +924,9 @@ class Button extends Component { -Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components. +クラスコンポーネントでの `this.context` の読み取りは、関数コンポーネントの [`useContext`](/reference/react/useContext) と同等です。 -[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function) +[移行方法を見る](#migrating-a-component-with-context-from-a-class-to-a-function) @@ -934,9 +934,9 @@ Reading `this.context` in class components is equivalent to [`useContext`](/refe ### `static defaultProps` {/*static-defaultprops*/} -You can define `static defaultProps` to set the default props for the class. They will be used for `undefined` and missing props, but not for `null` props. +クラスのデフォルトの props を設定するために `static defaultProps` を定義できます。これらは `undefined` および存在しない props に対して使用されますが、`null` である props には使用されません。 -For example, here is how you define that the `color` prop should default to `'blue'`: +例えば以下のようにして、props である `color` がデフォルトで `'blue'` になるよう定義できます。 ```js {2-4} class Button extends Component { @@ -950,7 +950,7 @@ class Button extends Component { } ``` -If the `color` prop is not provided or is `undefined`, it will be set by default to `'blue'`: +`color` prop が渡されない場合や `undefined` である場合、デフォルトで `'blue'` にセットされます。 ```js <> @@ -970,7 +970,7 @@ If the `color` prop is not provided or is `undefined`, it will be set by default -Defining `defaultProps` in class components is similar to using [default values](/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop) in function components. +クラスコンポーネントで `defaultProps` を定義することは、関数コンポーネントで[デフォルト値](/learn/passing-props-to-a-component#specifying-a-default-value-for-a-prop)を使用するのと同様のものです。 @@ -978,7 +978,7 @@ Defining `defaultProps` in class components is similar to using [default values] ### `static propTypes` {/*static-proptypes*/} -You can define `static propTypes` together with the [`prop-types`](https://www.npmjs.com/package/prop-types) library to declare the types of the props accepted by your component. These types will be checked during rendering and in development only. +コンポーネントが受け入れる props の型を宣言するために、[`prop-types`](https://www.npmjs.com/package/prop-types) ライブラリと一緒に `static propTypes` を定義することができます。これらの型はレンダー中、かつ開発中にのみチェックされます。 ```js import PropTypes from 'prop-types'; @@ -998,7 +998,7 @@ class Greeting extends React.Component { -We recommend using [TypeScript](https://www.typescriptlang.org/) instead of checking prop types at runtime. +ランタイムでの props の型チェックの代わりに [TypeScript](https://www.typescriptlang.org/) を使用することをお勧めします。 @@ -1006,27 +1006,27 @@ We recommend using [TypeScript](https://www.typescriptlang.org/) instead of chec ### `static getDerivedStateFromError(error)` {/*static-getderivedstatefromerror*/} -If you define `static getDerivedStateFromError`, React will call it when a child component (including distant children) throws an error during rendering. This lets you display an error message instead of clearing the UI. +`static getDerivedStateFromError` を定義すると、子コンポーネント(遠くの子を含む)がレンダー中にエラーをスローしたときに React がそれを呼び出します。これにより、UI をクリアする代わりにエラーメッセージを表示できます。 -Typically, it is used together with [`componentDidCatch`](#componentdidcatch) which lets you send the error report to some analytics service. A component with these methods is called an *error boundary.* +通常これは、エラーレポートを何らかの分析サービスに送信できるようにするための [`componentDidCatch`](#componentdidcatch) と一緒に使用されます。これらのメソッドを持つコンポーネントのことを*エラーバウンダリ*と呼びます。 -[See an example.](#catching-rendering-errors-with-an-error-boundary) +[例を見る](#catching-rendering-errors-with-an-error-boundary) -#### Parameters {/*static-getderivedstatefromerror-parameters*/} +#### 引数 {/*static-getderivedstatefromerror-parameters*/} -* `error`: The error that was thrown. In practice, it will usually be an instance of [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) but this is not guaranteed because JavaScript allows to [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) any value, including strings or even `null`. +* `error`: スローされたエラー。現実的には通常 [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) のインスタンスになりますが、このことは保証されていません。JavaScript では文字列や `null` すら含む、任意の値を [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) することが許されているためです。 -#### Returns {/*static-getderivedstatefromerror-returns*/} +#### 返り値 {/*static-getderivedstatefromerror-returns*/} -`static getDerivedStateFromError` should return the state telling the component to display the error message. +`static getDerivedStateFromError` からは、エラーメッセージを表示するようコンポーネントに指示するための state を返します。 -#### Caveats {/*static-getderivedstatefromerror-caveats*/} +#### 注意点 {/*static-getderivedstatefromerror-caveats*/} -* `static getDerivedStateFromError` should be a pure function. If you want to perform a side effect (for example, to call an analytics service), you need to also implement [`componentDidCatch`.](#componentdidcatch) +* `static getDerivedStateFromError` は純関数であるべきです。副作用(例えば、分析サービスの呼び出し)を実行したい場合は、[`componentDidCatch`](#componentdidcatch) も実装する必要があります。 -There is no direct equivalent for `static getDerivedStateFromError` in function components yet. If you'd like to avoid creating class components, write a single `ErrorBoundary` component like above and use it throughout your app. Alternatively, use the [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) package which does that. +関数コンポーネントには `static getDerivedStateFromError` に直接対応するものはまだありません。クラスコンポーネントの作成をなるべく避けたい場合は、上記のような `ErrorBoundary` コンポーネントを 1 つだけ書いてアプリ全体で使用します。あるいはこれを代わりにやってくれる [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) パッケージを使用することもできます。 @@ -1034,9 +1034,9 @@ There is no direct equivalent for `static getDerivedStateFromError` in function ### `static getDerivedStateFromProps(props, state)` {/*static-getderivedstatefromprops*/} -If you define `static getDerivedStateFromProps`, React will call it right before calling [`render`,](#render) both on the initial mount and on subsequent updates. It should return an object to update the state, or `null` to update nothing. +`static getDerivedStateFromProps` を定義すると、React は初回のマウントとその後の更新の両方で、[`render`](#render) を呼び出す直前にこれを呼び出します。state を更新するためのオブジェクトを返すか、何も更新しない場合は `null` を返すようにします。 -This method exists for [rare use cases](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state) where the state depends on changes in props over time. For example, this `Form` component resets the `email` state when the `userID` prop changes: +このメソッドは、state が props の経時的な変化に依存するという[稀なユースケース](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state)のために存在します。例えば、この `Form` コンポーネントは props である `userID` が変更されたときに state である `email` をリセットします。 ```js {7-18} class Form extends Component { @@ -1062,46 +1062,46 @@ class Form extends Component { } ``` -Note that this pattern requires you to keep a previous value of the prop (like `userID`) in state (like `prevUserID`). +このパターンでは、(`userID` のような)props の前回の値を、(`prevUserID` のような)state に保持する必要があることに注意してください。 -Deriving state leads to verbose code and makes your components difficult to think about. [Make sure you're familiar with simpler alternatives:](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html) +state 値の派生はコードを冗長にし、コンポーネントを分かりづらくします。[よりシンプルな代替手段について確実に理解しておいてください](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html)。 -- If you need to **perform a side effect** (for example, data fetching or an animation) in response to a change in props, use [`componentDidUpdate`](#componentdidupdate) method instead. -- If you want to **re-compute some data only when a prop changes,** [use a memoization helper instead.](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization) -- If you want to **"reset" some state when a prop changes,** consider either making a component [fully controlled](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component) or [fully uncontrolled with a key](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key) instead. +- props の変更に応じて**副作用を実行**する必要がある場合(例えば、データの取得やアニメーション)、代わりに [`componentDidUpdate`](#componentdidupdate) メソッドを使用してください。 +- **一部の props が変更されたときだけデータを再計算**する必要がある場合、[代わりにメモ化ヘルパーを使用します](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization)。 +- props が変更されたときに**ある state を「リセット」する**必要がある場合、コンポーネントを[完全に制御されたコンポーネント](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-controlled-component)にするか、[key 付きの非制御コンポーネント](https://legacy.reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key)にすることを検討してください。 -#### Parameters {/*static-getderivedstatefromprops-parameters*/} +#### 引数 {/*static-getderivedstatefromprops-parameters*/} -- `props`: The next props that the component is about to render with. -- `state`: The next state that the component is about to render with. +- `props`: コンポーネントがレンダーしようとしている次の props。 +- `state`: コンポーネントがレンダーしようとしている次の state。 -#### Returns {/*static-getderivedstatefromprops-returns*/} +#### 返り値 {/*static-getderivedstatefromprops-returns*/} -`static getDerivedStateFromProps` return an object to update the state, or `null` to update nothing. +`static getDerivedStateFromProps` は、state を更新するためのオブジェクトを返すか、何も更新しない場合は `null` を返します。 -#### Caveats {/*static-getderivedstatefromprops-caveats*/} +#### 注意点 {/*static-getderivedstatefromprops-caveats*/} -- This method is fired on *every* render, regardless of the cause. This is different from [`UNSAFE_componentWillReceiveProps`](#unsafe_cmoponentwillreceiveprops), which only fires when the parent causes a re-render and not as a result of a local `setState`. +- このメソッドは、原因に関係なく*すべての*レンダーで発火します。[`UNSAFE_componentWillReceiveProps`](#unsafe_cmoponentwillreceiveprops) はこれとは異なり、親が再レンダーを引き起こしたときのみ発火し、ローカルの `setState` の結果としては発火しません。 -- This method doesn't have access to the component instance. If you'd like, you can reuse some code between `static getDerivedStateFromProps` and the other class methods by extracting pure functions of the component props and state outside the class definition. +- このメソッドはコンポーネントのインスタンスにアクセスできません。お望みであれば、コンポーネントの props と state に対する純関数をクラス定義の外部に抽出することで、`static getDerivedStateFromProps` と他のクラスメソッドとの間でコードを再利用することができます。 -Implementing `static getDerivedStateFromProps` in a class component is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component. +クラスコンポーネントで `static getDerivedStateFromProps` を実装することは、関数コンポーネントでレンダー中に [`useState` の `set` 関数を呼び出す](/reference/react/useState#storing-information-from-previous-renders) ことと同等です。 --- -## Usage {/*usage*/} +## 使用法 {/*usage*/} -### Defining a class component {/*defining-a-class-component*/} +### クラスコンポーネントを定義する {/*defining-a-class-component*/} -To define a React component as a class, extend the built-in `Component` class and define a [`render` method:](#render) +React のコンポーネントをクラスとして定義するには、組み込みの `Component` クラスを継承し、[`render` メソッド](#render)を定義します。 ```js import { Component } from 'react'; @@ -1113,9 +1113,9 @@ class Greeting extends Component { } ``` -React will call your [`render`](#render) method whenever it needs to figure out what to display on the screen. Usually, you will return some [JSX](/learn/writing-markup-with-jsx) from it. Your `render` method should be a [pure function:](https://en.wikipedia.org/wiki/Pure_function) it should only calculate the JSX. +React は、画面に何を表示するかを知るために、[`render`](#render) メソッドを呼び出します。通常、そこからは [JSX](/learn/writing-markup-with-jsx) を返します。`render` メソッドは[純関数](https://en.wikipedia.org/wiki/Pure_function)である、つまり JSX の計算のみを行う必要があります。 -Similarly to [function components,](/learn/your-first-component#defining-a-component) a class component can [receive information by props](/learn/your-first-component#defining-a-component) from its parent component. However, the syntax for reading props is different. For example, if the parent component renders ``, then you can read the `name` prop from [`this.props`](#props), like `this.props.name`: +[関数コンポーネントと同様に](/learn/your-first-component#defining-a-component)、クラスコンポーネントでも親コンポーネントから [props を通じて情報を受け取る](/learn/your-first-component#defining-a-component)ことができます。ただし、props を読み取るための構文は異なります。例えば、親コンポーネントが `` をレンダーする場合、この `name` プロパティは [`this.props`](#props) から `this.props.name` のようにして読み取ります。 @@ -1141,19 +1141,19 @@ export default function App() { -Note that Hooks (functions starting with `use`, like [`useState`](/reference/react/useState)) are not supported inside class components. +フック(`use` で始まる [`useState`](/reference/react/useState) のような関数)はクラスコンポーネント内ではサポートされていないことに注意してください。 -We recommend defining components as functions instead of classes. [See how to migrate.](#migrating-a-simple-component-from-a-class-to-a-function) +クラスの代わりに関数でコンポーネントを定義することを推奨します。[移行方法はこちら](#migrating-a-simple-component-from-a-class-to-a-function)。 --- -### Adding state to a class component {/*adding-state-to-a-class-component*/} +### クラスコンポーネントに state を追加する {/*adding-state-to-a-class-component*/} -To add [state](/learn/state-a-components-memory) to a class, assign an object to a property called [`state`](#state). To update state, call [`this.setState`](#setstate). +クラスに [state](/learn/state-a-components-memory) を追加するには、[`state`](#state) というプロパティにオブジェクトを割り当てます。state を更新するには、[`this.setState`](#setstate) を呼び出します。 @@ -1203,21 +1203,21 @@ button { display: block; margin-top: 10px; } -We recommend defining components as functions instead of classes. [See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function) +クラスの代わりに関数でコンポーネントを定義することを推奨します。[移行方法はこちら](#migrating-a-component-with-state-from-a-class-to-a-function)。 --- -### Adding lifecycle methods to a class component {/*adding-lifecycle-methods-to-a-class-component*/} +### クラスコンポーネントにライフサイクルメソッドを追加する {/*adding-lifecycle-methods-to-a-class-component*/} -There are a few special methods you can define on your class. +クラスにはいくつかの特別なメソッドを定義することができます。 -If you define the [`componentDidMount`](#componentdidmount) method, React will call it when your component is added *(mounted)* to the screen. React will call [`componentDidUpdate`](#componentdidupdate) after your component re-renders due to changed props or state. React will call [`componentWillUnmount`](#componentwillunmount) after your component has been removed *(unmounted)* from the screen. +[`componentDidMount`](#componentdidmount) メソッドを定義すると、コンポーネントが画面に追加される(*マウントされる*)ときに React がそれを呼び出します。props や state の変更によりコンポーネントが再レンダーされた後に、React は [`componentDidUpdate`](#componentdidupdate) を呼び出します。コンポーネントが画面から削除される(*アンマウントされる*)際に、React は [`componentWillUnmount`](#componentwillunmount) を呼び出します。 -If you implement `componentDidMount`, you usually need to implement all three lifecycles to avoid bugs. For example, if `componentDidMount` reads some state or props, you also have to implement `componentDidUpdate` to handle their changes, and `componentWillUnmount` to clean up whatever `componentDidMount` was doing. +`componentDidMount` を実装する場合、通常はバグを避けるために 3 つすべてのライフサイクルを実装する必要があります。例えば、`componentDidMount` が何らかの state や props を読み取る場合はそれらに変更があった場合に処理するために `componentDidUpdate` を実装する必要があり、`componentDidMount` が実行したことをクリーンアップするためには `componentWillUnmount` を実装する必要があります。 -For example, this `ChatRoom` component keeps a chat connection synchronized with props and state: +例えば、以下の `ChatRoom` コンポーネントは、チャットへの接続を props および state と同期させています。 @@ -1333,21 +1333,21 @@ button { margin-left: 10px; } -Note that in development when [Strict Mode](/reference/react/StrictMode) is on, React will call `componentDidMount`, immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does. +開発時に [Strict Mode](/reference/react/StrictMode) が有効の場合、React は `componentDidMount` を呼び出し、直後に `componentWillUnmount` を呼び出し、その後再び `componentDidMount` を呼び出します。これにより、`componentWillUnmount` の実装を忘れた場合や、そのロジックが `componentDidMount` の挙動と正しく「鏡のように対応」していない場合に気づきやすくなります。 -We recommend defining components as functions instead of classes. [See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function) +クラスの代わりに関数でコンポーネントを定義することを推奨します。[移行方法はこちら](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function)。 --- -### Catching rendering errors with an error boundary {/*catching-rendering-errors-with-an-error-boundary*/} +### エラーバウンダリでレンダー中のエラーをキャッチする {/*catching-rendering-errors-with-an-error-boundary*/} -By default, if your application throws an error during rendering, React will remove its UI from the screen. To prevent this, you can wrap a part of your UI into an *error boundary*. An error boundary is a special component that lets you display some fallback UI instead of the part that crashed--for example, an error message. +デフォルトでは、アプリケーションがレンダー中にエラーをスローすると、React はその UI を画面から削除します。これを防ぐために、UI を*エラーバウンダリ*にラップすることができます。エラーバウンダリは、クラッシュした部位の代わりに、例えばエラーメッセージなどのフォールバック UI を表示するための、特別なコンポーネントです。 -To implement an error boundary component, you need to provide [`static getDerivedStateFromError`](#static-getderivedstatefromerror) which lets you update state in response to an error and display an error message to the user. You can also optionally implement [`componentDidCatch`](#componentdidcatch) to add some extra logic, for example, to log the error to an analytics service. +エラーバウンダリコンポーネントを実装するためには、エラーに反応して state を更新し、ユーザにエラーメッセージを表示するための [`static getDerivedStateFromError`](#static-getderivedstatefromerror) を提供する必要があります。またオプションで、例えばエラーを分析サービスに記録するなどの追加のロジックを追加するために [`componentDidCatch`](#componentdidcatch) を実装することもできます。 ```js {7-10,12-19} class ErrorBoundary extends React.Component { @@ -1381,7 +1381,7 @@ class ErrorBoundary extends React.Component { } ``` -Then you can wrap a part of your component tree with it: +次に、コンポーネントツリーの一部をこれでラップします。 ```js {1,3} Something went wrong

}> @@ -1389,25 +1389,25 @@ Then you can wrap a part of your component tree with it:
``` -If `Profile` or its child component throws an error, `ErrorBoundary` will "catch" that error, display a fallback UI with the error message you've provided, and send a production error report to your error reporting service. +もし `Profile` あるいはその子コンポーネントがエラーをスローすると、`ErrorBoundary` はそのエラーを「キャッチ」し、指定したエラーメッセージとともにフォールバック UI を表示し、エラーレポートをあなたのエラーレポーティングサービスに送信します。 -You don't need to wrap every component into a separate error boundary. When you think about the [granularity of error boundaries,](https://www.brandondail.com/posts/fault-tolerance-react) consider where it makes sense to display an error message. For example, in a messaging app, it makes sense to place an error boundary around the list of conversations. It also makes sense to place one around every individual message. However, it wouldn't make sense to place a boundary around every avatar. +すべてのコンポーネントを別々のエラーバウンダリでラップする必要はありません。[エラーバウンダリの粒度](https://www.brandondail.com/posts/fault-tolerance-react)について考える際は、エラーメッセージをどこに表示するのが理にかなっているかを考えてみてください。例えば、メッセージングアプリでは、会話のリストをエラーバウンダリで囲むのが理にかなっています。また、メッセージを個別に囲むことも理にかなっているでしょう。しかし、アバターを 1 つずつ囲むことには意味がありません。 -There is currently no way to write an error boundary as a function component. However, you don't have to write the error boundary class yourself. For example, you can use [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) instead. +現在、関数コンポーネントとしてエラーバウンダリを書く方法はありません。しかし、自分でエラーバウンダリクラスを書く必要はありません。例えば、代わりに [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) を使用することができます。 --- -## Alternatives {/*alternatives*/} +## 代替案 {/*alternatives*/} -### Migrating a simple component from a class to a function {/*migrating-a-simple-component-from-a-class-to-a-function*/} +### シンプルなコンポーネントをクラスから関数へ移行 {/*migrating-a-simple-component-from-a-class-to-a-function*/} -Typically, you will [define components as functions](/learn/your-first-component#defining-a-component) instead. +一般的には[コンポーネントは関数として定義](/learn/your-first-component#defining-a-component)します。 -For example, suppose you're converting this `Greeting` class component to a function: +例えば、この `Greeting` クラスコンポーネントを関数に書き換えたいとします。 @@ -1433,7 +1433,7 @@ export default function App() { -Define a function called `Greeting`. This is where you will move the body of your `render` function. +`Greeting` という関数を定義してください。ここに `render` 関数の本体を移動します。 ```js function Greeting() { @@ -1441,7 +1441,7 @@ function Greeting() { } ``` -Instead of `this.props.name`, define the `name` prop [using the destructuring syntax](/learn/passing-props-to-a-component) and read it directly: +`this.props.name` とする代わりに、props である `name` は[分割代入構文を使用して定義](/learn/passing-props-to-a-component)し、直接読み取ります: ```js function Greeting({ name }) { @@ -1449,7 +1449,7 @@ function Greeting({ name }) { } ``` -Here is a complete example: +完全な例は以下の通りです。 @@ -1473,9 +1473,9 @@ export default function App() { --- -### Migrating a component with state from a class to a function {/*migrating-a-component-with-state-from-a-class-to-a-function*/} +### state を持つコンポーネントをクラスから関数へ移行 {/*migrating-a-component-with-state-from-a-class-to-a-function*/} -Suppose you're converting this `Counter` class component to a function: +この `Counter` クラスコンポーネントを関数に書き換えたいとします。 @@ -1523,7 +1523,7 @@ button { display: block; margin-top: 10px; } -Start by declaring a function with the necessary [state variables:](/reference/react/useState#adding-state-to-a-component) +まず、必要となる [state 変数](/reference/react/useState#adding-state-to-a-component) を持った関数を宣言します。 ```js {4-5} import { useState } from 'react'; @@ -1534,7 +1534,7 @@ function Counter() { // ... ``` -Next, convert the event handlers: +次に、イベントハンドラを書き換えます。 ```js {5-7,9-11} function Counter() { @@ -1551,9 +1551,9 @@ function Counter() { // ... ``` -Finally, replace all references starting with `this` with the variables and functions you defined in your component. For example, replace `this.state.age` with `age`, and replace `this.handleNameChange` with `handleNameChange`. +最後に、`this` で始まる値への参照をすべて、コンポーネントで定義した変数と関数に置き換えます。例えば、`this.state.age` を `age` に、`this.handleNameChange` を `handleNameChange` に置き換えます。 -Here is a fully converted component: +完全に書き換えられたコンポーネントはこちらです。 @@ -1595,9 +1595,9 @@ button { display: block; margin-top: 10px; } --- -### Migrating a component with lifecycle methods from a class to a function {/*migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function*/} +### ライフサイクルメソッドを持つコンポーネントをクラスから関数へ移行 {/*migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function*/} -Suppose you're converting this `ChatRoom` class component with lifecycle methods to a function: +ライフサイクルメソッドを持つ以下の `ChatRoom` クラスコンポーネントを関数に書き換えたいとします。 @@ -1713,11 +1713,11 @@ button { margin-left: 10px; } -First, verify that your [`componentWillUnmount`](#componentwillunmount) does the opposite of [`componentDidMount`.](#componentdidmount) In the above example, that's true: it disconnects the connection that `componentDidMount` sets up. If such logic is missing, add it first. +まずは [`componentWillUnmount`](#componentwillunmount) が [`componentDidMount`](#componentdidmount) の逆の動作をしていることを確認してください。上記の例では `componentDidMount` によって確立された接続を切断しているので、そうなっています。そのようなロジックが存在しない場合、まずそれを追加してください。 -Next, verify that your [`componentDidUpdate`](#componentdidupdate) method handles changes to any props and state you're using in `componentDidMount`. In the above example, `componentDidMount` calls `setupConnection` which reads `this.state.serverUrl` and `this.props.roomId`. This is why `componentDidUpdate` checks whether `this.state.serverUrl` and `this.props.roomId` have changed, and resets the connection if they did. If your `componentDidUpdate` logic is missing or doesn't handle changes to all relevant props and state, fix that first. +次に、[`componentDidUpdate`](#componentdidupdate) メソッドが、`componentDidMount` で使用している props と state の変更を処理していることを確認してください。上記の例では、`componentDidMount` は `setupConnection` を呼び出しており、それが `this.state.serverUrl` と `this.props.roomId` を読み取っています。したがって `componentDidUpdate` も `this.state.serverUrl` と `this.props.roomId` が変更されたかどうかを確認し、変更があった場合は接続を再確立しなければなりません。`componentDidUpdate` のロジックが存在しない、あるいは関連するすべての props と state の変更を処理できていない場合は、まずそれを修正してください。 -In the above example, the logic inside the lifecycle methods connects the component to a system outside of React (a chat server). To connect a component to an external system, [describe this logic as a single Effect:](/reference/react/useEffect#connecting-to-an-external-system) +上記の例では、ライフサイクルメソッド内のロジックは、React の外部のシステム(チャットサーバ)にコンポーネントを接続しています。コンポーネントを外部システムに接続するためには、[このロジックを単一のエフェクトとして記述します](/reference/react/useEffect#connecting-to-an-external-system)。 ```js {6-12} import { useState, useEffect } from 'react'; @@ -1737,7 +1737,7 @@ function ChatRoom({ roomId }) { } ``` -This [`useEffect`](/reference/react/useEffect) call is equivalent to the logic in the lifecycle methods above. If your lifecycle methods do multiple unrelated things, [split them into multiple independent Effects.](/learn/removing-effect-dependencies#is-your-effect-doing-several-unrelated-things) Here is a complete example you can play with: +この [`useEffect`](/reference/react/useEffect) の呼び出しは、上記のライフサイクルメソッド内のロジックと同等です。ライフサイクルメソッドが複数の互いに関連しないことを行っている場合は、[それらを複数の独立したエフェクトに分割してください](/learn/removing-effect-dependencies#is-your-effect-doing-several-unrelated-things)。以下に完全な例を示します。 @@ -1824,15 +1824,15 @@ button { margin-left: 10px; } -If your component does not synchronize with any external systems, [you might not need an Effect.](/learn/you-might-not-need-an-effect) +コンポーネントが外部システムとの同期を行わない場合、[エフェクトは必要ないかもしれません](/learn/you-might-not-need-an-effect)。 --- -### Migrating a component with context from a class to a function {/*migrating-a-component-with-context-from-a-class-to-a-function*/} +### コンテクストを持つコンポーネントをクラスから関数へ移行 {/*migrating-a-component-with-context-from-a-class-to-a-function*/} -In this example, the `Panel` and `Button` class components read [context](/learn/passing-data-deeply-with-context) from [`this.context`:](#context) +以下の例では、クラスコンポーネントである `Panel` と `Button` が、[`this.context`](#context) から[コンテクスト](/learn/passing-data-deeply-with-context)を読み取っています。 @@ -1926,7 +1926,7 @@ export default function MyApp() { -When you convert them to function components, replace `this.context` with [`useContext`](/reference/react/useContext) calls: +これらを関数コンポーネントに変換する場合、`this.context` を [`useContext`](/reference/react/useContext) の呼び出しに置き換えます。