Skip to content

Latest commit

 

History

History
165 lines (117 loc) · 12.8 KB

GettingStarted.md

File metadata and controls

165 lines (117 loc) · 12.8 KB

Начало работы с Redux

Redux - это контейнер с предсказуемым состоянием для приложений JavaScript.

Он помогает вам писать приложения, которые ведут себя согласованно, работают в разных средах (клиентских, серверных и нативные приложения) и которые легко тестировать. Кроме того, он предоставляет отличные возможности для разработчиков, такие как редактирование кода в реальном времени в сочетании с отладчиком time traveling.

Вы можете использовать Redux вместе с React или с любой другой библиотекой представлений. Он крошечный (2 КБ, включая зависимости), но имеет большую экосистему доступных дополнений.

Установка

Redux доступен в качестве NPM-пакета для с использования со сборщиками модулей или в Noe-приложении:

# NPM
npm install --save redux

# Yarn
yarn add redux

Он также доступен в виде предварительно скомпилированного пакета UMD, который объявляет глобальную переменную window.Redux. Пакет UMD может использоваться непосредственно как тег <script>

Redux Toolkit

Redux сам по себе маленький и ненавязчивый.

У нас также есть отдельный пакет дополнений под названием Redux Toolkit, который включает в себя некоторые неконтролируемые значения по умолчанию, которые помогают вам более эффективно использовать Redux. Это наш официальный рекомендуемый подход для написания логики Redux.

RTK includes utilities that help simplify many common use cases, including store setup, creating reducers and writing immutable update logic, and even creating entire "slices" of state at once.

Whether you're a brand new Redux user setting up your first project, or an experienced user who wants to simplify an existing application, Redux Toolkit can help you make your Redux code better.

Basic Example

The whole state of your app is stored in an object tree inside a single store.
The only way to change the state tree is to emit an action, an object describing what happened.
To specify how the actions transform the state tree, you write pure reducers.

That's it!

import { createStore } from 'redux'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() => console.log(store.getState()))

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions. Then you write a special function called a reducer to decide how every action transforms the entire application's state.

In a typical Redux app, there is just a single store with a single root reducing function. As your app grows, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. This is exactly like how there is just one root component in a React app, but it is composed out of many small components.

This architecture might seem like an overkill for a counter app, but the beauty of this pattern is how well it scales to large and complex apps. It also enables very powerful developer tools, because it is possible to trace every mutation to the action that caused it. You can record user sessions and reproduce them just by replaying every action.

Example Projects

The Redux repository contains several example projects demonstrating various aspects of how to use Redux. Almost all examples have a corresponding CodeSandbox sandbox. This is an interactive version of the code that you can play with online.

See the complete list of examples in the Examples page.

Learn Redux

We have a variety of resources available to help you learn Redux, no matter what your background or learning style is.

Just the Basics

If you're brand new to Redux and want to understand the basic concepts, see:

Intermediate Concepts

Once you've picked up the basics of working with actions, reducers, and the store, you may have questions about topics like working with asynchronous logic and AJAX requests, connecting a UI framework like React to your Redux store, and setting up an application to use Redux:

Real-World Usage

Going from a TodoMVC app to a real production application can be a big jump, but we've got plenty of resources to help:

Help and Discussion

The #redux channel of the Reactiflux Discord community is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - come join us!

You can also ask questions on Stack Overflow using the #redux tag.

If you have a bug report or need to leave other feedback, please file an issue on the Github repo

Should You Use Redux?

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Don't use Redux just because someone said you should - take some time to understand the potential benefits and tradeoffs of using it.

Here are some suggestions on when it makes sense to use Redux:

  • You have reasonable amounts of data changing over time
  • You need a single source of truth for your state
  • You find that keeping all your state in a top-level component is no longer sufficient

For more thoughts on how Redux is meant to be used, see: