-
原理
react数据改变是通过state来处理的,而添加redux是为了通过一个store统一管理state数据变化,单向数据流:
action->reducer->store-> state
-
原料
-
redux
用于创建store,创建reducer, 管理日志打印,用到方法(createStore, combineReducers, createLogger)
-
react-redux: Provider
用于将Store绑定在项目上
-
redux-thunk
中间件,用于异步处理
-
redux-logger
用与打印日志
-
-
项目结构
src
|-- store
|-- reducers
|-- middleware
|-- components
|-- container
|-- common
-
项目搭建
-
创建单个reducer,在reducers文件夹下添加count.js,并新增如下代码
const initialState = { num: 0 } export default (state = initialState, action) => { switch (aciton.type) { case "ADD": /**可建立一个actionType.js用常量定义aciton*/ retrun { num: state.num + 1 } } }
-
将单个reducer并合在一起,如刚刚新添加的(count.js),在reducers文件夹下添加index.js
import { combineReducers } from "redux"; import count from "./count" export default combineReducers({ count, })
-
创建store,在store文件夹下添加configureStore.js
import { createStore,applyMiddleware } from "redux" import thunk from "redux-thunk" import { createLogger } from "redux-logger" import rootReducer from "../reducers" export default function configureStore(preloadedState) { const store = createStore( rootReducer, preloadedState, /**初始state,可省略*/ applyMiddleware(thunk, createLogger({ duration: 1000, predicate: ture, /**判断日志打印条件如:生产环境*/ stateTransfomer: (state) => { var result = {} Object.keys(state).filter( key => { if (state[key].toJS) { result[key] = state[key].toJS() } else { result[key] = state[key] } }) return reuslt } }) ) }
-
项目中添加store,用于管理state,在根目录的index.js中改写
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import { Provider } from "react-redux" import configureStore from "./store/configureStore" const stores = configureStore({}) ReactDOM.render( <Provider store={stores}> <App /> </Provider>, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
-
在页面中通过action更改数据 connect是将store中(state, dispatch)传入页面,动态渲染页面
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { connect } from "react-redux" class App extends Component { constructor(props) { super(props) console.log("prop", props) } render() { return ( <div className="App"> <div>{this.props.num}</div> <div onClick={this.props.add}>+++++</div> </div> ); } } function mapStateToProps(state) { const { count } = state console.log("sss", count) return { num: count.num } } function mapDispatchToProps(dispatch) { return { add: () => dispatch({ type: "ADD" }) } } export default connect(mapStateToProps, mapDispatchToProps)(App);
网友评论