Before, I used zhihu Daily’S API to write an introduction project of React Native, and sent the article address of react Native introduction project and source address of RN introduction project source code. Currently, the code on Github has added new functions on the basis of the original text, which is the advanced content of this article. After reading this article interested students can refer to it.

thinking

In the introduction project, we have practiced the basic usage of React Native, showing the list and details page of Zhihu Daily. This is of course not a problem in small projects, where we request the network and render components on each page. However, when the project becomes complex and needs to add new Feather or extend base modules such as log, this practice can be extremely painful and will result in less effort.

From a maintenance and functional extension perspective, it is imperative that the project use the appropriate framework. For example, we need to record the logs of all network access in the system. If fetch is used to access the network in each page, the log needs to be recorded in each page:

1.png





2.png

This approach already works for the most part; when the log requirements change, you can simply follow a new module.

If you need to add database access logs, you can define a database access module in the same vein, and define the corresponding logging module in this module. If you need to add more types of logging modules, do you continue along the same lines?

Let’s take a look at the two types of logging mentioned just now and extract the similarities. Both types need to be logged. Is it possible to extract a log module?

3.png

If another requirement is to record the execution time of all operations and adjust the corresponding system parameters according to the statistics of the execution time, how to solve this problem? We can add another module in the middle:

4.png


Flux

5.png


  • View: The View layer
  • Action: Messages sent by the view layer (such as mouseClick)
  • Dispatcher: Receives Actions and performs callbacks
  • Store: It stores the status of the app and reminds Views to update the page when it changes

Its basic idea is to encapsulate all actions, and then distribute them with dispatcher. After processing them in Store, they are transmitted to View to complete a complete data flow, which is one-way and irreversible. Action is understood as an Action, which not only includes Action type (i.e. target, log recording or task execution time calculation), but also can carry certain data. Refer to figure 4 of our thinking above, which is very in line with our needs.

Redux

Redux is actually an implementation of the Flux train of thought, slightly different in terms of role definitions, but not preventing the same train of thought.

  • Action is similar to the definition in Flux
  • Reducer is defined as state to update actions. Note that only reduce can update actions in the process. Meanwhile, Reducer should ensure that it is a pure function, that is, for certain inputs, corresponding outputs can be obtained without being affected by time or due to it.
  • Store Store actually completes the functions of dispatcher and connects other functional modules.

    Maintain application state; Provide the getState() method to getState; Provide a dispatch(action) method to update state; Register a listener with subscribe(listener); Unsubscribe the listener via a function returned by subscribe(listener).

Another important concept of Redux is middleware, which can perform additional actions during data transfer, such as logging mentioned above. At this point, we can use Redux to do what we need. This article mainly introduces the ideas, about redux specific learning recommended teacher Ruan Yifeng’s blog, Redux introductory tutorial.

redux-saga

We know that there will be a lot of asynchronous operations in the application, such as network access, data reading, etc. Redux does the transferring of data, but the asynchronous part of the operation can be messy if we don’t pay attention to it, and Redux-Saga has done that.

Sagas are responsible for coordinating complex or asynchronous operations.

The project practice

The next step in this article is to add support for Redux to the code, which is not necessary for the purpose of the project but simply adds complexity to the project. This is a demonstration of the use of Redux and the middleware redux-Saga and Redux-Logger in the project. Saga has been introduced above. The Redux Logger actually records all the Action states. When debugging the project, we can determine the specific state changes of the project according to the log output of the console:

Paste_Image.png

  • The creation of a store
const middlewares = [];
/ / create a reducer
const rootReducer = combineReducers({story});
// Create middleware saga
const sagaMiddleware = saga();

middlewares.push(sagaMiddleware)
if (process.env.NODE_ENV === 'development') {
    // Create middleware Logger
    const logger = createLogger();
    middlewares.push(logger);
}
// Applymiddleware configures middleware
constcreateStoreWithMiddleware = applyMiddleware(... middlewares)(createStore);function createDefaultStore(initialsState) {
    // Obtain STARE from the reducer
    const defaultStore = createStoreWithMiddleware(rootReducer, initialsState);
    return defaultStore;
}
const store = createDefaultStore();Copy the code
  • Creation of Reducers Can create multiple Reducers through

    combineReducers();Copy the code

    Are combined

    const initialState = {
      id: "".refreshing: true.loaded: false.story: new Object()
    };
    export default function story(state = initialState, action) {
      switch (action.type) {
          case ActionType.Fetch_Story_Detail:
              return Object.assign({}, state, {
                  id: action.id,
                  refreshing: true.loaded: false
              });
          case ActionType.Fetch_Story_Detail_Done:
              return Object.assign({}, state, {
                  id: action.id,
                  refreshing: false.load: true.story: action.story
              });
          default:
              returnstate; }}Copy the code

    Create a Store reducer as shown above

  • Connect interface components require Connect Redux, can dispatch Actions, and can receive corresponding callbacks to render the interface.

    function mapStateToProps(state) {
      const {story} = state;
      return {
          story
      };
    }
    StoryDetailPage.propTypes = propTypes;
    export default connect(mapStateToProps)(StoryDetailPage);Copy the code

    After these steps, the structure of our project is very clear, and it is easy to do module maintenance and extension.

Code Address:react-native-zhihu

Please pay attention to the public account Wutongke, and push the cutting-edge technology articles of mobile development every day:

wutongke

Recommended reading:

React Native Project Introduction (Zhihu Daily, Douban Film, [one] one) React Native project Introduction (Redux, Redux Saga, Redux Logger)

React Native Project 2 (One client)

Thank you: www.ruanyifeng.com/blog/2016/0… www.ruanyifeng.com/blog/2016/0… Github.com/kenberkeley… Leonshi.com/redux-saga-… cn.redux.js.org/index.html