Redux状态机:

  redux管理数据,单独得js,可以和react一起使用,也可以不和react一起使用。

  1. React项目很小,简单不复杂,就一两个人开发,就不需要redux.
  2. 安装

  npm install --save redux

  1. 单页面使用:
    1. 新建reducer

  指定了应用状态的变化如何响应 actions 并发送到 store 的,记住 actions 只是描述了有事情发生了这一事实,并没有描述应用如何更新 state。

const counter = (state=0,action={}) =>{

   switch(action.type){

      case 'INCRMENT':

          return state + 1;

      case "DECREMENT":

           return state -1;

      default: return state;

   }

}

export default counter;

 

  1. 引入redux

import reportWebVitals from './reportWebVitals';

import {createStore} from "redux";

import reducer from "./reducers/counts";

  const store = createStore(reducer); 创建store,并传入reducer

根据已有的 reducer 来创建 store 是非常容易的。在前一个章节中,我们使用 combineReducers() 将多个 reducer 合并成为一个。现在我们将其导入,并传递 createStore()

   改造一下这个组件

 

    Action 是把数据从应用(译者注:这里之所以不叫 view 是因为这些数据有可能是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch()  action 传到 store。

const render = () => {

  ReactDOM.render(

      <App 

      onIncrment = {() => store.dispatch({type: "INCRMENT"}) }  

      onDecrement = {() => store.dispatch({type: "DECREMENT"})}

      value={store.getState()} />,

    document.getElementById('root')

  );

}

render();

  store.subscribe(render);实现监听

   添加一个变化监听器。每当 dispatch action 的时候就会执行,state 树中的一部分可能已经变化。你可以在回调函数里调用 getState() 来拿到当前 state。

   listener (Function): 每当 dispatch action 的时候都会执行的回调。state 树中的一部分可能已经变化。你可以在回调函数里调用 getState() 来拿到当前 state。store 的 reducer 应该是纯函数,因此你可能需要对 state 树中的引用做深度比较来确定它的值是否有变化。

 

参考网址:http://cn.redux.js.org/docs/basics/Store.html

5.react-redux数据传递到component

  npm install react-redux

  import {createStore} from "redux";

// import reducer from "./reducers/counts";

import rootReducer from "./reducers";

import {incrment,decrment} from "./actions";

import {Provider} from "react-redux";

 

const store = createStore(rootReducer);

 

//store.subscribe(() => console.log("State updated!",store.getState()));

 

ReactDOM.render(

<Provider store={store}>

Provider组件作为做上层组件,需要将store作为参数注入组件中,此后在子组件中都可以访问到store这个对象;connect方法接受两个参数:mapStateToProps,actionCreators,并返回处理后的组件,其中mapStateToProps可以将对应的state作为prop注入对应的子组件,actionCreator可以将对应的actioncreator作为prop注入对应的子组件

      <App/>

    </Provider>,

    document.getElementById('root')

);

 

Reducdrs:

import {combineReducers} from "redux"; 

import counter from './counts';

import user from "./user";

//combineReducers Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 Reducer。

const rootReducer = combineReducers({

    counter,

    user

});

export default rootReducer

 

下层:

import {connect} from "react-redux";

 

获取到:

 <h1 className="jumbotron-heading text-center">

             {this.props.counter}

           </h1>

 

mapStateToProps可以将对应的state作为prop注入对应的子组件

const mapStateToProps = (state) => {

  console.log("state",state);

  return {

    counter: state.counter

  }

}

//connect高阶组件 React-Redux提供一个connect方法能够让你把组件和store连接起来。

export default connect(mapStateToProps)(App);

 

 

  1. DispatchAction

  Component子组件可以用dispatch调用action,并传递相对应得单个参数,以及对象:

  Constructor里打印:

console.log("props",props);发现有dispatch这个方法

定义好action方法里得传递参数:

 export const incrment = (name) => {

    return {

        type: type.INCRMENT,

        name

    }

}

 

export const decrment = () => {

    return {

        type: type.DECREMENT

    }

}

 

     

 

       Component调用dispatch,并传递对应得单个参数,多个参数

<p className="text-center">

             <button onClick={() => dispatch(incrment({name:"小猪",id:2}))}  className="btn btn-primary my-2">新增</button> 

             <button onClick={() => dispatch(decrment())} className="btn btn-danger my-2">减少</button>

           </p>

   设置reducers得时候打印一下:

   case 'INCRMENT':

          console.log("action",action); 打印action

          return state + 1;

 

 

  1. mapDispatchToProps(教程作者提示,这个不太友好)

const mapDispatchToProps = (dispatch) => {

  return {

    add:(name) => { dispatch(incrment(name))}

  }

}

 

export default connect(mapStateToProps,mapDispatchToProps)(App);

//使用这个mapDispatchToProps,就不能从props里获取到dispatch了,可以拿到自定义得add方法,进行使用

const {add} = this.props;

<button onClick={() => add("杀尽天下有情人")}  className="btn btn-primary my-2">新增</button> 

 

  1. bindActionCreators比上一种简洁一些:

// const mapDispatchToProps = (dispatch) => {

//     return {

//       add: bindActionCreators(incrment,dispatch)

//     }

// }

 

const mapDispatchToProps = (dispatch) => {

  return  bindActionCreators({incrment},dispatch)

}

export default connect(mapStateToProps,mapDispatchToProps)(App);

还可以:

export default connect(mapStateToProps,{incrment,decrment})(App);

  1. 中间件:

  Logger

  //中间件:

 const logger = store => next => action => {

  console.log("dispatching",action);

  let result = next(action);

  console.log('next state',store.getState());

  return result;

}

 

//createStore (1参数:reducer 

//            ,2参数:initialState初始时的 state

//            ,3参数:enhancer 是一个组合 store creator 的高阶函数,返回一个新的强化过的 store creator。这与 middleware 相似,它也允许你通过复合函数改变 store 接口。

//             )

const store = createStore(rootReducer,{},applyMiddleware(logger));

  1. 异步yarn add redux-thunk

   发送ajax请求:

   yarn add axios

    axios.get("https://randomuser.me/api123")

        .then(res => {

            console.log(res.data.results);

            dispatch(fetch_user(res.data.results[0]));

        })

        .catch(error => {

            //console.log(error)

            dispatch(fetch_user_failure(error.response.data));

        })

11.redux-promise-middleware

  用来处理异步的中间件为 redux-promise-middleware ,相比较 redux-promise 它保留了乐观更新的能力。在启用它之后,我们可以触发一个 payload 属性为 promise 对象的 action

  const foo = () => ({

  type: 'FOO',

  payload: new Promise()

})

异步操作action得3个状态,PEDING加载,FULFILLED成功,REJECATED失败

switch (action.type) {

    case 'MY_ACTION_TYPE_PENDING':

        return {...state, myActionLoading: true}

    case 'MY_ACTION_TYPE_FULFILLED':

        return {...state, xxx,  myActionLoading: false}

    case 'MY_ACTION_TYPE_REJECTED':

        return {...state, myActionLoading: false}

}

redux-promise-middleware 处理过程,当有异步事件开始或者状态改变时,我们除了触发原来的事件外,也触发一个特殊事件的 action,它携带当前事件的 type  状态 作为参数, 当接收到这个事件后我们把这个 reducer 对应的 type 的状态改为参数的的状态。这样我们就可以自动的更新每一个 action 目前的状态值了。

12.打包:

   npm build 或者 npm run build

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/historylyt/p/14636992.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程