When should I add Redux to a React app?

2019-01-20 23:29发布

I'm currently learning React and I am trying to figure out how to use it with Redux for building a mobile app. I'm kind of confused on how the two are related/usable together. For example, I completed this tutorial in React https://www.raywenderlich.com/99473/introducing-react-native-building-apps-javascript, but now I want to play around with adding some reducers/actions to that app and I am not sure where those would tie in with what I've already done.

6条回答
Animai°情兽
2楼-- · 2019-01-20 23:54

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.

查看更多
再贱就再见
3楼-- · 2019-01-20 23:58

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!

查看更多
趁早两清
4楼-- · 2019-01-20 23:59

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.)

查看更多
The star\"
5楼-- · 2019-01-21 00:06

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

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

ACTIONS- Actions are payloads of information that send data from your application to the store. They are the only source of information fro 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 that 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 ato the dispatch() function.

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

Alernativly you can create a bound action creator that autometically dispatches.

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

now you can disrectly called him

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 applciation 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 an sction, 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

查看更多
smile是对你的礼貌
6楼-- · 2019-01-21 00:10

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.

查看更多
戒情不戒烟
7楼-- · 2019-01-21 00:17

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

查看更多
登录 后发表回答