我应该何时将 Redux 添加到 React 应用程序?

我目前正在学习的反应,我试图找出如何使用它与 Redux 建立一个移动应用程序。我有点搞不懂这两者是怎么联系在一起的。例如,我在 React https://www.raywenderlich.com/99473/introducing-react-native-building-apps-javascript中完成了这个教程,但是现在我想在这个应用程序中添加一些减速器/动作,我不确定这些应用程序和我已经完成的应用程序是否有关联。

22150 次浏览

React is a UI framework that takes care of updating the UI in response to the “source of truth” that is usually described as a state “owned” by some component. Thinking in React describes the React state ownership concept very well, and I strongly suggest you go through it.

This state ownership model works well when the state is hierarchical and more or less matches the component structure. This way the state gets “spread out” across many components, and the app is easy to understand.

However sometimes distant parts of the app want to have access to the same state, for example, if you cache fetched data and want to consistently update it everywhere at the same time. In this case, if you follow the React model, you’ll end up with a bunch of very large components at the top of the component tree that pass a myriad of props down through some intermediate components that don’t use them, just to reach a few leaf components that actually care about that data.

When you find yourself in this situation, you can (but don’t have to) use Redux to “extract” this state management logic from the top-level components into separate functions called “reducers”, and “connect” the leaf components that care about that state directly to it instead of passing the props through the whole app. If you don’t have this problem yet, you probably don’t need Redux.

Finally, note that Redux is not a definitive solution to this problem. There are many other ways to manage your local state outside the React components—for example, some people who didn’t like Redux are happy with MobX. I would suggest you to first get a firm understanding of React state model, and then evaluate different solutions independently, and build small apps with them to get a sense of their strengths and weaknesses.

(This answer is inspired by Pete Hunt’s react-howto guide, I suggest you to read it as well.)

I've found that the ideal path for adding Redux to an application/stack is to wait until after you/app/team are feeling the pains that it solves. Once you start seeing long chains of props building up and being passed down through multiple levels of components or your finding yourself orchestrating complex state manipulations/reads, that could be a sign that your app may benefit from introducing Redux et al.

I recommend taking an app that you've already built with "just React" and see how Redux might fit into it. See if you can gracefully introduce it by plucking out one piece of state or set of "actions" at a time. Refactor towards it, without getting hung up on a big bang rewrite of your app. If you're still having trouble seeing where it might add value, then that could be a sign that your app is either not large or complex enough to merit something like Redux on top of React.

If you haven't come across it yet, Dan (answered above) has a great short-video series that walks through Redux on a more fundamental level. I highly suggest spending some time absorbing pieces of it: https://egghead.io/series/getting-started-with-redux

Redux also has some pretty great docs. Especially explaining a lot of the "why" such as http://redux.js.org/docs/introduction/ThreePrinciples.html

Firstly, you don't need to add Redux to your application if you don't need it! Simple, so don't force yourself to include it in your project if you don't need it at all! But that doesn't mean Redux is no good, it's really helpful in large applications, so read on ...

Redux is a state management for your React application, think about Redux like a local store which track of your state as you go, you can access the state in any page and route you want, also compare to Flux, you only have one store, means one source of truth...

Look at this image to understand what Redux does first at a glance:

enter image description here

Also this's how Redux introduce itself:

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies).

Also as per documentation, there are Three Principles for Redux as below:

1. Single source of truth

2. State is read-only

3. Changes are made with pure functions

So basically when you need to a single store to keep track of anything you like in your application, then Redux is handy, you can access it anywhere in your app, in any route... simply using store.getState();

Also using the middleware Redux, you can do manage the state much better, there a list of handy components and middleware on official page of Redux!

Simply if your application gonna be big, with many components, states and routing try to implements Redux from start! It will help you on the way for sure!

When we write application we need to manage state of the application. The React manages states locally within the component if we need to share the states between components we can use props or callbacks.

But as application grows it becomes difficult to manage states and state transformations.State and state transformations need to properly tracked in order to debug the applications.

Redux is a predictable state container for JavaScript apps that manages state and state transformations and is often used with React,

The concept of redux can be explained in following image.

Redux

When user triggers an action when user interact with the component and an action is dispatched to store then the reducer in the store accepts the action and update the state of the application and stored in the application wide immutable global variable when there is an update in store the corresponding view component subscribed to the state will get updated.

Since state is managed globally and with redux it is easier to maintain.

enter image description here

This is how redux works. A action is dispatched from any compoenent or view. Action MUST have "type" property and may be any property which holds information of action happened. The data passed in action, could be relevant to different reducer, so same object get passed to different reducer. Each reducer takes/ make-out its part/contribution to state. The output is then merged and new state get formed, and the component which must be subscribed for state change event gets notified.

In above example, brown color has all 3 component RGB. Each reducer receives same brown color and they seperate out its contribution to the color.

I have prepared this document to understand Redux. Hope this clears your doubt.

-------------------------- REDUX TUTORIAL ----------------------

ACTIONS- Actions are payloads of information that send data from your application to the store. They are the only source of information from the store. You can send them only using store.dispatch().

   Example-
const  ADD_TODO = 'ADD_TODO'


{
type:ADD_TODO,
text: 'Build my first redux app'
}

Actions are plain javascript object. Action must have a [ type ] property that indicates the type of action being performed. The type should be defined as a string constant.

ACTION CREAToRS----- ---------------- ---- Action creators are exactly the function that creates action It is easy to conflate the terms - action and action creator. In redux action, creator returns an action.

function addToDo(text) {
return {
type: ADD_TODO,
text
}
}

to initialte dispatch pass the result to the dispatch() function.

  1. dispatch(addToDo(text));
  2. dispatch(completeToDo(index))

Alternatively, you can create a bound action creator that automatically dispatches.

cosnt boundAddTodO = text => dispatch(addToDo(text));

now you can directly called it

boundaddTodO(text);

The dispatch() functionn can be directly accessed from store.dispatch(). but we access it using a helper connect() method.

Actions.js.....................

Actions...........

exports cosnt ADD_TODO = 'ADD_TODO';
exports cosnt TOGGLE_TODO = 'TOGGLE_TODO'

Actions Creators

export function addToDO(text){ return { type: ADD_TODO, text } }


.........................REDUCERS..................................

Reducers specify how the applications state changes in response to actions sent to the store.

Designing the state shap

In redux all the application state is store in single object. You have to store some data as well as some state.

{ visibilityFilter: 'SHOW_ALL', todos: [ { text: 'Consider using redux', completed: true }, { text: 'Kepp all the state in single tree' } ] }

Handling Actions ---------------- the reducers are the pure functions that take the previous state and action, and return a new state.

(previousState, action) => newState

We will start by specifying the initial state. Redux will call our reducers with an undefined state for the first time. this is our chance to return the state of our app.

import  { visiblilityFilters } from './actions';
const initialState = {
visibilityFilter: VisibilityFilters.SHOW_ALL,
todo: []
}


function todoApp(state, action){
if(typeof state == 'undefined'){
return initialState;
}


// dont handle other cases as of now.
return state;
}

you can do the same using ES6 way of handling the JS

function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}

................................. STORE...................................

The store is a object that brings them together. the store has following responsbility

  1. hold application state
  2. allow access to state via getState()
  3. Allow state to be updated via dispatch()
  4. Register listerneres via suscriber(listener)

Note. use combineReducers() to combine several reducers into one.

const store = createStore(todoapp); // the todoapp are the reducers

Having used Redux and personally finding it cumbersome, I found passing around an object to my components as a prop can be a much easier way to maintain state. Not to mention it's an easy way of making references to functions to call in other components. It can solve a lot of the cumbersome issues of passing messages between components in React, so it's a two for one.