redux使用步骤

-
安装redux:npm install redux 或者 yarn add redux
-
创建store:通过redux的createStore方法创建一个store,其中需要传入reducer函数作为参数,reducer函数用来处理不同的action。
-
创建reducer:reducer是一个纯函数,接收两个参数,一个是当前的state,一个是action。reducer的作用是根据action的类型更新state。
-
创建action:action是一个对象,其中必须包含一个type属性,表示该action的类型。action可以携带一些数据,用来更新state。
-
发送action:通过调用store.dispatch(action)方法来发送action,触发reducer的执行,更新state。
-
获取state:通过调用store.getState()方法来获取当前的state。
-
监听state的变化:可以通过调用store.subscribe(listener)方法来监听state的变化,listener会在每次state更新时被调用。
-
应用中间件(可选):通过调用redux的applyMiddleware方法来应用中间件,中间件可以增强redux的功能,比如异步操作、日志记录等。
-
连接React组件:通过react-redux库提供的connect方法来连接React组件和redux,connect会将store中的state和dispatch方法传递给组件。
原文地址: http://www.cveoy.top/t/topic/dvED 著作权归作者所有。请勿转载和采集!