react native 之 redux

第一章  认识redux

    说的通俗且直白一点呢,就是redux提供了一个store,独立的一个内存区,然后放了一些state,你可以在任何component中访问到state,这些state要更改怎么办呢,store提供了reducer,reducer就是一些函数(纯函数),通过action来对state进行更改,并返回新state。component中如何调用reducer呢,通过dispatch(action),分发action,这样就自动进入对action进行操作的reducer函数了。

第二章 redux 中的reducer

   reducer 中有布尔值,可以用来判断

    1.reducer 的格式

    首先,定义state数据的格式,然后是初始化 state:

     一般是用type 

export type State = {
  username: string,
  password: string,
  isLoading: boolean,
  errors: [],
  isLoggedIn: false,
}

     初始化state:

const initialState = {
  username: "",
  password: "",
  isLoading: false,
  errors: [],
  isLoggedIn: false,
}

然后是reducer 不断的增加调用action中的那些function,

export default function (state:State = initialState, action: Action) {
  if (action.type === 'SET_USER_NAME') {
    return {
      ...state,
      username: action.username,
    }
  }
  if (action.type === 'SET_PASSWORD') {
    return {
      ...state,
      password: action.password,
    }
  }
  if (action.type === 'LOGIN_START_LOADING') {
    return {
      ...state,
      isLoading: true,
    }
  }
  if (action.type === 'LOGIN_LOADED') {
    return {
      ...state,
      isLoading: false,
      isLoggedIn: true,
    }
  }
  if (action.type === 'LOGIN_ERROR') {
    return {
      ...state,
      isLoading: false,
      errors: [...state.errors, action.loginError]
    }
  }
  return state
}

注意:reducer  中只有action  与state 两个参数

第三章.redux  中的action

    首先,定义action     

export type Action = { type: 'SET_USER_NAME', username: string }
  | { type: 'SET_PASSWORD', password: string }
  | { type: 'LOGIN_START_LOADING' }
  | { type: 'LOGIN_LOADED', loginData: Object }
  | { type: 'LOGIN_ERROR', error: Object }

export function usernameAction(username) {
  return {
    type: 'SET_USER_NAME',
    username,
  };
}

export function passwordAction(password) {
  return {
    type: 'SET_PASSWORD',
    password,
  }
}

     然后页面中通过dispatch  去调用这些function  返回action处理完后最新的数据,并将这些运用dispatch的函数绑定傻瓜component

function mapProps(storeState) {
  const {username, password} = storeState;
  const isValid = username.length > 6 && password.length > 6;
  return {
    ...storeState,
    isValid,
  }
}

function mapActions(dispatch) {
  return {

    onUsernameChange: (username) => dispatch(usernameAction(username)),
    onPasswordChange: (password) => dispatch(passwordAction(password)),
    onLoginPress: ()=>dispatch(loginAction),

  }
}


export default connect(mapProps, mapActions)(App);

 最后,总结下运行的过程是:

 主页通过dispatch引入action获取action处理完后的数据,渲染到页面中,reducer引入相关的action,使用action相关函数获取的state去改变store 里面的函数    

     action 文件被双向的引入.


  

   

原文地址:https://www.cnblogs.com/leyan/p/5765704.html