From 2c9717deed25d09106508f28f2ea5cc7fe995422 Mon Sep 17 00:00:00 2001 From: Anton Ahatov Date: Tue, 30 Jul 2019 20:30:29 +0300 Subject: [PATCH] Resolve conflicts eef56ffd (#367) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update thinking-in-react.md (#2095) Please refer to https://justsimply.dev for the thinking behind these proposed changes. * Update thinking-in-react.md (#2098) Follow up to https://github.com/reactjs/reactjs.org/pull/2095#discussion_r296498172 * Add missing function call to example (#2102) An example for useEffect omitted the actual invocation of the function in question. * Add description of PropTypes.exact (#1581) Info from https://github.com/facebook/prop-types#usage * Improve grammar (#2106) * Fixed minor code-splitting.md typo (#1292) * Fixed minor code-splitting.md typo * Update code-splitting.md Co-authored-by: Alexey Pyltsyn * Fixed broken link to discuss.react.org (#2107) * Replaced broken discuss.reactjs.org link On the how-to-contribute page, there is a broken link under the https://reactjs.org/docs/how-to-contribute.html#how-to-get-in-touch section. As outlined in https://github.com/reactjs/reactjs.org/issues/2080 `discuss.reactjs.org` isn't reachable. I edited the text to display `Discussion Forums` which links to https://reactjs.org/community/support.html#popular-discussion-forums (as I was unable to find an official reactjs discussion forum). * fixed text case changed `Discussion Forums` to `Discussion forums` * Update 2019-02-23-is-react-translated-yet.md (#2109) * Add Meetup (#2097) Add JaipurJS - JavaScript meetup in Jaipur, Rajasthan, India * [docs] Updated required node and npm versions to match CRA docs in 'docs/create-a-new-react-app.html' (#2099) https://facebook.github.io/create-react-app/docs/getting-started * Remove tooling support info in fragment docs (#2096) * Correct the description of when gDSFP gets called (#2100) * Added free Scrimba React Tutorial (#2111) A great video/editor tutorial consisting of 48 hands-on lessons. * Update Production Optimization docs to use terser (#2112) * Update Production Optimization docs to use terser * Update Optimizing Performance.md * Fix typo Co-Authored-By: Alexey Pyltsyn * Update hooks-faq.md (#2113) * Update hooks-faq.md I tripped up slightly while reading this example for using the callback form of a state setter inside an effect. I've added a few lines that might help a hook newbie grok the differences between the examples. * Update hooks-faq.md * Update hooks-faq.md * Update tutorial.md (#2115) changed 'any React apps' to 'any React app' * move past conferences to the bottom of the list (#2118) * fix(Blog): Post title updated to correct word for yes word in spanish (#2122) * Revert "fix(Blog): Post title updated to correct word for yes word in spanish (#2122)" (#2130) This reverts commit 06a029d53d7ee7e5e717dd39450ac6af1ff554e5. * Add DevExtreme Reactive to the Components list (#2127) * [Documentation] Fix: Update link to Chrome Accessibility Inspec… (#2134) * React Native added support for hooks in 0.59 (#2121) * React Native added support for hooks in 0.59 React Native 0.59 and above already support React Hooks, this line is no longer necessary, causes confusion for some people that it is not working right now. We can also mention React Native version if needed. * update with react native mention of hooks support * Update content/docs/hooks-faq.md suggested changes Co-Authored-By: Alexey Pyltsyn * Add Kiel to the list of React Meetups (#2136) * Reduce confusion about adding additional fields to .this (#2142) As a new React learner, this part was a bit confusing as I though that it was referencing `() => this.tick()` part of the code. My addition would help at least people like me. * Added option for more cdns. (#2144) * Update docs about an existence of .elementType (#2145) Hi, I've met the same issue on [here](https://github.com/facebook/prop-types/issues/200) at storybook and found the following [PR](https://github.com/facebook/prop-types/pull/211) that adds the `elementType` feature. It could find the doc on npm, but not the official react site. * Revert "Added option for more cdns. (#2144)" (#2146) This reverts commit b84fb3d281220b226b8eab38e84720ff82c3cc12. * Add React Conf to list of community conferences (#2158) * Add React Conf to list of community conferences * Whoops, put right day in * docs(hooks): fix typo (#2161) * update the status of Arabic translation .. (#2157) * Fixing typo in contributing section of the docs (#2166) * Add a relevant FAQ link in "Thinking In React" (#2170) --- .../2018-03-27-update-on-async-rendering.md | 2 +- .../2019-02-23-is-react-translated-yet.md | 4 +- content/community/conferences.md | 65 ++++++++++--------- content/community/courses.md | 2 + content/community/meetups.md | 2 + content/community/tools-ui-components.md | 1 + content/docs/code-splitting.md | 4 +- content/docs/create-a-new-react-app.md | 2 +- content/docs/fragments.md | 4 +- content/docs/hooks-faq.md | 7 +- content/docs/how-to-contribute.md | 3 +- content/docs/optimizing-performance.md | 47 +++++++------- content/docs/state-and-lifecycle.md | 2 +- content/docs/thinking-in-react.md | 4 +- content/docs/typechecking-with-proptypes.md | 9 +++ content/languages.yml | 2 +- 16 files changed, 87 insertions(+), 73 deletions(-) diff --git a/content/blog/2018-03-27-update-on-async-rendering.md b/content/blog/2018-03-27-update-on-async-rendering.md index de19850ee..8fd58a456 100644 --- a/content/blog/2018-03-27-update-on-async-rendering.md +++ b/content/blog/2018-03-27-update-on-async-rendering.md @@ -134,7 +134,7 @@ Here is an example of a component that uses the legacy `componentWillReceiveProp Although the above code is not problematic in itself, the `componentWillReceiveProps` lifecycle is often mis-used in ways that _do_ present problems. Because of this, the method will be deprecated. -As of version 16.3, the recommended way to update `state` in response to `props` changes is with the new `static getDerivedStateFromProps` lifecycle. (That lifecycle is called when a component is created and each time it receives new props): +As of version 16.3, the recommended way to update `state` in response to `props` changes is with the new `static getDerivedStateFromProps` lifecycle. It is called when a component is created and each time it re-renders due to changes to props or state: `embed:update-on-async-rendering/updating-state-from-props-after.js` You may notice in the example above that `props.currentRow` is mirrored in state (as `state.lastRow`). This enables `getDerivedStateFromProps` to access the previous props value in the same way as is done in `componentWillReceiveProps`. diff --git a/content/blog/2019-02-23-is-react-translated-yet.md b/content/blog/2019-02-23-is-react-translated-yet.md index 3ac56a5a4..f88698a66 100644 --- a/content/blog/2019-02-23-is-react-translated-yet.md +++ b/content/blog/2019-02-23-is-react-translated-yet.md @@ -23,7 +23,7 @@ In the past, React community members have created unofficial translations for [C If you would like to help out on a current translation, check out the [Languages](/languages) page and click on the "Contribute" link for your language. -Can't find your language? If you'd like to maintain your langauge's translation fork, follow the instructions in the [translation repo](https://github.com/reactjs/reactjs.org-translation#starting-a-new-translation)! +Can't find your language? If you'd like to maintain your language's translation fork, follow the instructions in the [translation repo](https://github.com/reactjs/reactjs.org-translation#starting-a-new-translation)! ## Backstory {#backstory} @@ -39,7 +39,7 @@ This approach appealed to us for several reasons: * It encouraged active maintainers for each repo to ensure quality. * Contributors already understand GitHub as a platform and are motivated to contribute directly to the React organization. -We started of with an initial trial period of three languages: Spanish, Japanese, and Simplified Chinese. This allowed us to work out any kinks in our process and make sure future translations are set up for success. I wanted to give the translation teams freedom to choose whatever tools they felt comfortable with. The only requirement is a [checklist](https://github.com/reactjs/reactjs.org-translation/blob/master/PROGRESS.template.md) that outlines the order of importance for translating pages. +We started off with an initial trial period of three languages: Spanish, Japanese, and Simplified Chinese. This allowed us to work out any kinks in our process and make sure future translations are set up for success. I wanted to give the translation teams freedom to choose whatever tools they felt comfortable with. The only requirement is a [checklist](https://github.com/reactjs/reactjs.org-translation/blob/master/PROGRESS.template.md) that outlines the order of importance for translating pages. After the trial period, we were ready to accept more languages. I created [a script](https://github.com/reactjs/reactjs.org-translation/blob/master/scripts/create.js) to automate the creation of the new language repo, and a site, [Is React Translated Yet?](https://isreacttranslatedyet.com), to track progress on the different translations. We started *10* new translations on our first day alone! diff --git a/content/community/conferences.md b/content/community/conferences.md index febeb0755..2c388b523 100644 --- a/content/community/conferences.md +++ b/content/community/conferences.md @@ -12,36 +12,6 @@ Do you know of a local React.js conference? Add it here! (Please keep the list c ## Upcoming Conferences {#upcoming-conferences} -### ReactEurope 2019 {#reacteurope-2019} -May 23-24, 2019 in Paris, France - -[Website](https://www.react-europe.org) - [Twitter](https://twitter.com/ReactEurope) - [Facebook](https://www.facebook.com/ReactEurope) - [Videos](https://www.youtube.com/c/ReacteuropeOrgConf) - -### React Conf Armenia 2019 {#react-conf-am-19} -May 25, 2019 in Yerevan, Armenia - -[Website](https://reactconf.am/) - [Twitter](https://twitter.com/ReactConfAM) - [Facebook](https://www.facebook.com/reactconf.am/) - [YouTube](https://www.youtube.com/c/JavaScriptConferenceArmenia) - [CFP](http://bit.ly/speakReact) - -### ReactNext 2019 {#react-next-2019} -June 11, 2019. Tel Aviv, Israel - -[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w) - -### React Norway 2019 {#react-norway-2019} -June 12, 2019. Larvik, Norway - -[Website](https://reactnorway.com) - [Twitter](https://twitter.com/ReactNorway) - -### React Loop 2019 {#react-loop-2019} -June 21, 2019 Chicago, Illinois USA - -[Website](https://reactloop.com) - [Twitter](https://twitter.com/ReactLoop) - -### Chain React 2019 {#chain-react-2019} -July 11-12, 2019. Portland, OR, USA. - -[Website](https://infinite.red/ChainReactConf) - ### React Rally 2019 {#react-rally-2019} August 22-23, 2019. Salt Lake City, USA. @@ -82,6 +52,11 @@ September 26-28, 2019 in Alicante, Spain [Website](http://reactalicante.es/) - [Twitter](https://twitter.com/reactalicante) - [Facebook](https://www.facebook.com/ReactAlicante) +### React Conf 2019 {#react-conf-2019} +October 24-25, 2019 in Henderson, Nevada USA + +[Website](https://conf.reactjs.org/) - [Twitter](https://twitter.com/reactjs) + ### React Advanced 2019 {#react-advanced-2019} October 25, 2019 in London, UK @@ -395,3 +370,33 @@ May 3, 2019 in London, UK May 11 in Sofia, Bulgaria [Website](http://react-not-a-conf.com/) - [Twitter](https://twitter.com/reactnotaconf) - [Facebook](https://www.facebook.com/events/780891358936156) + +### ReactEurope 2019 {#reacteurope-2019} +May 23-24, 2019 in Paris, France + +[Website](https://www.react-europe.org) - [Twitter](https://twitter.com/ReactEurope) - [Facebook](https://www.facebook.com/ReactEurope) - [Videos](https://www.youtube.com/c/ReacteuropeOrgConf) + +### React Conf Armenia 2019 {#react-conf-am-19} +May 25, 2019 in Yerevan, Armenia + +[Website](https://reactconf.am/) - [Twitter](https://twitter.com/ReactConfAM) - [Facebook](https://www.facebook.com/reactconf.am/) - [YouTube](https://www.youtube.com/c/JavaScriptConferenceArmenia) - [CFP](http://bit.ly/speakReact) + +### ReactNext 2019 {#react-next-2019} +June 11, 2019. Tel Aviv, Israel + +[Website](https://react-next.com) - [Twitter](https://twitter.com/ReactNext) - [Videos](https://www.youtube.com/channel/UC3BT8hh3yTTYxbLQy_wbk2w) + +### React Norway 2019 {#react-norway-2019} +June 12, 2019. Larvik, Norway + +[Website](https://reactnorway.com) - [Twitter](https://twitter.com/ReactNorway) + +### React Loop 2019 {#react-loop-2019} +June 21, 2019 Chicago, Illinois USA + +[Website](https://reactloop.com) - [Twitter](https://twitter.com/ReactLoop) + +### Chain React 2019 {#chain-react-2019} +July 11-12, 2019. Portland, OR, USA. + +[Website](https://infinite.red/ChainReactConf) diff --git a/content/community/courses.md b/content/community/courses.md index cd05adea0..0de2c69d5 100644 --- a/content/community/courses.md +++ b/content/community/courses.md @@ -22,6 +22,8 @@ permalink: community/courses.html - [Free React Bootcamp](https://tylermcginnis.com/free-react-bootcamp/) - Recordings from three days of a free online React bootcamp. +- [Scrimba: Learn React for free](https://scrimba.com/g/glearnreact) - 48 hands-on video tutorials building react apps. + ## Paid Courses {#paid-courses} - [Egghead.io](https://egghead.io/browse/frameworks/react) - Short instructional videos on React and many other topics. diff --git a/content/community/meetups.md b/content/community/meetups.md index 6e78bc2f0..fc6c0e46a 100644 --- a/content/community/meetups.md +++ b/content/community/meetups.md @@ -55,6 +55,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Düsseldorf](https://www.meetup.com/de-DE/ReactJS-Meetup-Dusseldorf/) * [Hamburg](https://www.meetup.com/Hamburg-React-js-Meetup/) * [Karlsruhe](https://www.meetup.com/react_ka/) +* [Kiel](https://www.meetup.com/Kiel-React-Native-Meetup/) * [Munich](https://www.meetup.com/ReactJS-Meetup-Munich/) * [React Berlin](https://www.meetup.com/React-Berlin/) * [React.JS Girls Berlin](https://www.meetup.com/ReactJS-Girls-Berlin/) @@ -69,6 +70,7 @@ Do you have a local React.js meetup? Add it here! (Please keep the list alphabet * [Bangalore](https://www.meetup.com/ReactJS-Bangalore/) * [Chennai](https://www.meetup.com/React-Chennai/) * [Delhi NCR](https://www.meetup.com/React-Delhi-NCR/) +* [Jaipur](https://www.meetup.com/JaipurJS-Developer-Meetup/) ## Ireland {#ireland} * [Dublin](https://www.meetup.com/ReactJS-Dublin/) diff --git a/content/community/tools-ui-components.md b/content/community/tools-ui-components.md index 57367cf75..a0535c829 100644 --- a/content/community/tools-ui-components.md +++ b/content/community/tools-ui-components.md @@ -72,6 +72,7 @@ permalink: community/ui-components.html ## Fee Based Components {#fee-based-components} * **[ag-Grid](https://www.ag-grid.com)** Advanced data grid / data table for React. +* **[DevExtreme Reactive](https://devexpress.github.io/devextreme-reactive/react/)** High-performance plugin-based Data Grid, Scheduler and Chart components for Bootstrap and Material Design. * **[ExtReact components](https://www.sencha.com/products/extreact//)**: 115+ Ready-to-Use UI Components. * **[Grapecity Wijmo UI Components for React](https://www.grapecity.com/en/react/)**: Expand your React UI options with Wijmo’s complete collection of JavaScript components. * **[jQWidgets React components](https://www.jqwidgets.com/react/)**: Enterprise Ready 70+ UI Components. diff --git a/content/docs/code-splitting.md b/content/docs/code-splitting.md index 89480aabd..f328da74a 100644 --- a/content/docs/code-splitting.md +++ b/content/docs/code-splitting.md @@ -107,9 +107,7 @@ import("./math").then(math => { > Примечание: > -> Возможности `React.lazy` и задержки (suspense) пока недоступны для рендеринга на стороне сервера. -> Если вам нужно разделение кода в серверном приложении, мы рекомендуем [Loadable Components](https://github.com/smooth-code/loadable-components). -> У них есть хорошее [руководство по разделению бандла](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md) с серверным рендерингом. +> Возможности `React.lazy` и задержки (suspense) пока недоступны для рендеринга на стороне сервера. Если вам нужно разделение кода в серверном приложении, мы рекомендуем [Loadable Components](https://github.com/smooth-code/loadable-components). У них есть хорошее [руководство по разделению бандла](https://github.com/smooth-code/loadable-components/blob/master/packages/server/README.md) с серверным рендерингом. Функция `React.lazy` позволяет рендерить динамический импорт как обычный компонент. diff --git a/content/docs/create-a-new-react-app.md b/content/docs/create-a-new-react-app.md index d2c1f94a2..985b7d4ba 100644 --- a/content/docs/create-a-new-react-app.md +++ b/content/docs/create-a-new-react-app.md @@ -39,7 +39,7 @@ next: cdn-links.html [Create React App](https://github.com/facebookincubator/create-react-app) – удобная среда для **изучения React** и лучший способ начать создание **нового [одностраничного](/docs/glossary.html#single-page-application) приложения** на React. -Инструмент настраивает среду для использования новейших возможностей JavaScript, оптимизирует приложение для продакшена и обеспечивает комфорт во время разработки. Вам понадобятся Node.js не ниже версии 6 и npm не ниже версии 5.2 на вашем компьютере. Для создания проекта выполните команды: +Инструмент настраивает среду для использования новейших возможностей JavaScript, оптимизирует приложение для продакшена и обеспечивает комфорт во время разработки. Вам понадобятся Node.js не ниже версии 8.10 и npm не ниже версии 5.6 на вашем компьютере. Для создания проекта выполните команды: ```bash npx create-react-app my-app diff --git a/content/docs/fragments.md b/content/docs/fragments.md index 599ccaa40..80e7f40c9 100644 --- a/content/docs/fragments.md +++ b/content/docs/fragments.md @@ -18,7 +18,7 @@ render() { } ``` -Также существует [сокращённая запись](#short-syntax), однако не все популярные инструменты поддерживают её. +Также существует [сокращённая запись](#short-syntax). ## Мотивация {#motivation} @@ -113,8 +113,6 @@ class Columns extends React.Component { Можно использовать `<>` так же, как используется любой другой элемент. Однако такая запись не поддерживает ключи или атрибуты. -Обратите внимание, что **[большинство инструментов ещё не поддерживают сокращённую запись](/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax)**, поэтому можно явно указывать ``, пока не появится поддержка. - ### Фрагменты с ключами {#keyed-fragments} Фрагменты, объявленные с помощью ``, могут иметь ключи. Например, их можно использовать при создании списка определений, преобразовав коллекцию в массив фрагментов. diff --git a/content/docs/hooks-faq.md b/content/docs/hooks-faq.md index 85f84020d..bb629a046 100644 --- a/content/docs/hooks-faq.md +++ b/content/docs/hooks-faq.md @@ -70,7 +70,7 @@ prev: hooks-reference.html Обратите внимание, что **хуки будут доступны, только если все React-пакеты версии 16.8.0 или выше**. Хуки не будут работать, если вы, например, забыли обновить React DOM. -Поддержка хуков в React Native добавится в следующем стабильном релизе. +React Native 0.59 и выше поддерживает хуки. ### Надо ли переписать все мои классовые компоненты? {#do-i-need-to-rewrite-all-my-class-components} @@ -621,7 +621,6 @@ function ProductPage({ productId }) { const json = await response.json(); if (!ignore) setProduct(json); } - fetchProduct(); return () => { ignore = true }; }, [productId]); @@ -678,6 +677,8 @@ function Counter() { } ``` +Пустой набор зависимостей `[]` означает, что эффект будет выполняться только один раз, когда компонент монтируется, а не при каждом повторном рендере. Проблема в том, что внутри обратного вызова `setInterval` значение `count` не изменяется, потому что мы создали замыкание со значением `count`, установленным в `0`, как это было при выполнении обратного вызова эффекта. Каждую секунду этот обратный вызов вызывает `setCount(0 + 1)`, поэтому счетчик никогда не превышает 1. + Если переписать список зависимостей как `[count]`, то баг будет устранён, но это приведёт к сбрасыванию интервала при каждом изменении. Такое поведение может быть нежелательно. Чтобы исправить это, мы можем применить [форму функционального обновления хука `setState`](/docs/hooks-reference.html#functional-updates), которая позволяет указать, *как* должно меняться состояние, не ссылаясь явно на *текущее* состояние: ```js{6,9} @@ -697,6 +698,8 @@ function Counter() { (Идентичность функции `setCount` гарантирована, поэтому её можно безопасно не включать в список зависимостей.) +Теперь обратный вызов `setInterval` выполняется один раз в секунду, но каждый раз, когда внутренний вызов `setCount` может использовать обновленное значение для `count` (называемое `c` в обратном вызове здесь.) + В более сложных случаях (например, когда одно состояние зависит от другого), попробуйте перенести логику обновления состояния из хука эффекта в хук [`useReducer`](/docs/hooks-reference.html#usereducer). [Эта статья](https://adamrackis.dev/state-and-use-reducer/) иллюстрирует пример того, как это сделать. **Идентичность функции `dispatch` из хука `useReducer` всегда стабильна** — даже если функция редюсера объявлена внутри компонента и считывает его пропсы. В крайнем случае если вы хотите реализовать что-то наподобие `this` в классах, вы можете [использовать реф](/docs/hooks-faq.html#is-there-something-like-instance-variables), чтобы хранить в нём изменяемую переменную. Тогда можно писать и читать из него. Например: diff --git a/content/docs/how-to-contribute.md b/content/docs/how-to-contribute.md index cf5a3603e..d825461f8 100644 --- a/content/docs/how-to-contribute.md +++ b/content/docs/how-to-contribute.md @@ -50,9 +50,8 @@ React использует [семантическое версионирова У Facebook есть [программа Bug Bounty](https://www.facebook.com/whitehat/) для сообщения о багах безопасности. Пожалуйста, не публикуйте ишью о таких проблемах в открытом доступе. Если вы обнаружили дыру в безопасности React, зайдите на [эту страницу](https://www.facebook.com/whitehat/) и следуйте инструкциям. ### Наши контакты {#how-to-get-in-touch} - * IRC: [#reactjs на freenode](https://webchat.freenode.net/?channels=reactjs) -* Форум: [discuss.reactjs.org](https://discuss.reactjs.org/) +* [Форум](https://reactjs.org/community/support.html#popular-discussion-forums) Кроме этого есть [сообщество пользователей React на платформе чатов Discord](https://www.reactiflux.com/). Туда вы также можете обратиться за помощью. diff --git a/content/docs/optimizing-performance.md b/content/docs/optimizing-performance.md index bcfa87059..5bfaa8a33 100644 --- a/content/docs/optimizing-performance.md +++ b/content/docs/optimizing-performance.md @@ -51,14 +51,14 @@ npm run build ### Brunch {#brunch} -Для наиболее эффективной продакшен-сборки с Brunch, установите плагин [`uglify-js-brunch`](https://github.com/brunch/uglify-js-brunch). +Для наиболее эффективной продакшен-сборки с Brunch, установите плагин [`terser-brunch`](https://github.com/brunch/terser-brunch). ``` # В случае использования npm -npm install --save-dev uglify-js-brunch +npm install --save-dev terser-brunch # В случае использования Yarn -yarn add --dev uglify-js-brunch +yarn add --dev terser-brunch ``` Затем, для создания продакшен сборки, добавьте флаг `-p` к команде `build`: @@ -75,17 +75,17 @@ brunch build -p ``` # В случае использования npm -npm install --save-dev envify uglify-js uglifyify +npm install --save-dev envify terser uglifyify # В случае использования Yarn -yarn add --dev envify uglify-js uglifyify +yarn add --dev envify terser uglifyify ``` При создании продакшен-сборки, убедитесь, что вы добавили эти пакеты для преобразования **(порядок имеет значение)**: * Плагин [`envify`](https://github.com/hughsk/envify) обеспечивает правильную среду для сборки. Сделайте его глобальным (`-g`). * Плагин [`uglifyify`](https://github.com/hughsk/uglifyify) удаляет импорты, добавленные при разработке. Сделайте его глобальным (`-g`). -* Наконец, полученная сборка отправляется к [`uglify-js`](https://github.com/mishoo/UglifyJS2) для минификации ([прочитайте, зачем это нужно](https://github.com/hughsk/uglifyify#motivationusage)). +* Наконец, полученная сборка отправляется к [`terser`](https://github.com/terser-js/terser) для минификации ([прочитайте, зачем это нужно](https://github.com/hughsk/uglifyify#motivationusage)). К примеру: @@ -93,33 +93,28 @@ yarn add --dev envify uglify-js uglifyify browserify ./index.js \ -g [ envify --NODE_ENV production ] \ -g uglifyify \ - | uglifyjs --compress --mangle > ./bundle.js + | terser --compress --mangle > ./bundle.js ``` ->**Примечание:** -> ->Имя пакета `uglify-js`, но фактически он предоставляет исполняемый файл с именем `uglifyjs`.
->Это не опечатка. - Помните, что это нужно делать только для продакшен-сборки. Вам не следует использовать эти плагины в процессе разработки, потому что это скроет вспомогательные предупреждения React и замедлит процесс сборки. ### Rollup {#rollup} Для наиболее эффективной продакшен-сборки с Rollup, установите несколько плагинов: -``` +```bash # В случае использования npm -npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-uglify +npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser # В случае использования Yarn -yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-uglify +yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-terser ``` При создании продакшен-сборки, убедитесь, что вы добавили эти плагины **(порядок имеет значение)**: * Плагин [`replace`](https://github.com/rollup/rollup-plugin-replace) обеспечивает правильную среду для сборки. * Плагин [`commonjs`](https://github.com/rollup/rollup-plugin-commonjs) обеспечивает поддержку CommonJS в Rollup. -* Плагин [`uglify`](https://github.com/TrySound/rollup-plugin-uglify) сжимает и оптимизирует финальную сборку. +* Плагин [`terser`](https://github.com/TrySound/rollup-plugin-terser) сжимает и оптимизирует финальную сборку. ```js plugins: [ @@ -128,14 +123,14 @@ plugins: [ 'process.env.NODE_ENV': JSON.stringify('production') }), require('rollup-plugin-commonjs')(), - require('rollup-plugin-uglify')(), + require('rollup-plugin-terser')(), // ... ] ``` Полный пример настройки можно [посмотреть здесь](https://gist.github.com/Rich-Harris/cb14f4bc0670c47d00d191565be36bf0). -Помните, что это нужно делать только для продакшен-сборки. Вам не следует использовать плагин `uglify` или плагин `replace` со значением `'production'` в процессе разработки, потому что это скроет вспомогательные предупреждения React и замедлит процесс сборки. +Помните, что это нужно делать только для продакшен-сборки. Вам не следует использовать плагин `terser` или плагин `replace` со значением `'production'` в процессе разработки, потому что это скроет вспомогательные предупреждения React и замедлит процесс сборки. ### webpack {#webpack} @@ -144,18 +139,22 @@ plugins: [ >Если вы используете Create React App, пожалуйста, следуйте [инструкциям выше](#create-react-app).
>Этот раздел подойдёт для тех, кто самостоятельно настраивает webpack. -Для наиболее эффективной продакшен-сборки с помощью webpack обязательно включите эти плагины в конфигурацию: +Webpack v4 + будет минимизировать ваш код по умолчанию в продакшен-режиме. ```js -new webpack.DefinePlugin({ - 'process.env.NODE_ENV': JSON.stringify('production') -}), -new webpack.optimize.UglifyJsPlugin() +const TerserPlugin = require('terser-webpack-plugin'); + +module.exports = { + mode: 'production' + optimization: { + minimizer: [new TerserPlugin({ /* additional options here */ })], + }, +}; ``` Вы можете узнать об этом больше в [документации webpack](https://webpack.js.org/guides/production/). -Помните, что это нужно делать только для продакшен-сборки. Вам не стоит использовать `UglifyJsPlugin` или `DefinePlugin` со значением `'production'` в процессе разработки, потому что тогда скроются вспомогательные предупреждения React и замедлится процесс сборки. +Помните, что это нужно делать только для продакшен-сборки. Вам не стоит использовать `TerserPlugin` в процессе разработки, потому что тогда скроются вспомогательные предупреждения React и замедлится процесс сборки. ## Анализ производительности компонентов с помощью вкладки Chrome «Performance» {#profiling-components-with-the-chrome-performance-tab} diff --git a/content/docs/state-and-lifecycle.md b/content/docs/state-and-lifecycle.md index 39a675ef3..a945b963d 100644 --- a/content/docs/state-and-lifecycle.md +++ b/content/docs/state-and-lifecycle.md @@ -245,7 +245,7 @@ class Clock extends React.Component { } ``` -Обратите внимание, что мы сохраняем ID таймера в `this`. +Обратите внимание, что мы сохраняем ID таймера в `this` (`this.timerID`). Поля `this.props` и `this.state` в классах особенные, и их устанавливает сам React. Вы можете вручную добавить новые поля, если компоненту нужно хранить дополнительную информацию (например, ID таймера). diff --git a/content/docs/thinking-in-react.md b/content/docs/thinking-in-react.md index 6a8d30b0f..d62658daf 100644 --- a/content/docs/thinking-in-react.md +++ b/content/docs/thinking-in-react.md @@ -77,7 +77,7 @@ prev: composition-vs-inheritance.html ### Небольшое отступление: как пропсы отличаются от состояния {#a-brief-interlude-props-vs-state} -Существует два типа "модели" данных в React: пропсы и состояние. Важно, чтобы вы понимали разницу между ними, в противном случае обратитесь к [официальной документации React](/docs/interactivity-and-dynamic-uis.html). +Существует два типа "модели" данных в React: пропсы и состояние. Важно, чтобы вы понимали разницу между ними, иначе обратитесь к [официальной документации React](/docs/state-and-lifecycle.html). Посмотрите также раздел [Какая разница между state и props?](/docs/faq-state.html#what-is-the-difference-between-state-and-props) ## Шаг 3: Определим минимальное (но полноценное) отображение состояния интерфейса {#step-3-identify-the-minimal-but-complete-representation-of-ui-state} @@ -142,8 +142,6 @@ prev: composition-vs-inheritance.html Давайте подумаем, как мы хотим изменить поведение. Нам нужно, чтобы при изменениях поисковой формы менялось состояние ввода. Так как компоненты должны обновлять только относящееся к ним состояние, `FilterableProductTable` передаст колбэк в `SearchBar`. В свою очередь, `SearchBar` будет вызывать этот колбэк каждый раз, когда надо обновить состояние. Чтобы получать уведомления об изменениях элементов формы, мы можем использовать событие `onChange`. Колбэки, переданные из компонента `FilterableProductTable`, вызовут `setState()`, и приложение обновится. -Хоть и звучит сложно, но занимает это всего несколько строк кода. А главное, поток данных через приложение остаётся прямым и понятным. - ## Вот и всё {#and-thats-it} Надеемся, что этот пример поможет вам получить лучшее представление о том, как подойти к созданию компонентов и приложений в React. Хотя этот процесс и использует немного больше кода, помните: код читают чаще, чем пишут. А модульный и прямолинейный код читается значительно легче. Когда вы начнёте создавать большие библиотеки компонентов, вы сможете по-настоящему оценить прямолинейность и связанность React, а повторно используемые компоненты сделают ваш код намного меньше. :) diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index 5aeb59550..d9ac0bd53 100644 --- a/content/docs/typechecking-with-proptypes.md +++ b/content/docs/typechecking-with-proptypes.md @@ -58,6 +58,9 @@ MyComponent.propTypes = { // React-элемент optionalElement: PropTypes.element, + // Тиа React-элемент (MyComponent). + optionalElementType: PropTypes.elementType, + // Можно указать, что проп должен быть экземпляром класса // Для этого используется оператор `instanceof`. optionalMessage: PropTypes.instanceOf(Message), @@ -84,6 +87,12 @@ MyComponent.propTypes = { color: PropTypes.string, fontSize: PropTypes.number }), + + // An object with warnings on extra properties + optionalObjectWithStrictShape: PropTypes.exact({ + name: PropTypes.string, + quantity: PropTypes.number + }), // Можно добавить`isRequired` к любому из приведённому выше типу, // чтобы показывать предупреждение, diff --git a/content/languages.yml b/content/languages.yml index 268515d7a..6f957905f 100644 --- a/content/languages.yml +++ b/content/languages.yml @@ -10,7 +10,7 @@ - name: Arabic translated_name: العربية code: ar - status: 0 + status: 1 - name: Azerbaijani translated_name: Azərbaycanca code: az