react-redux应用

    xiaoxiao2021-12-15  6

    //reducers const reducer1 = (state = {"test":"nihao"}, action= {}) => { switch (action.type) { case 'xxx': default: return state; } } const reducer2 = (state = {}, action= {}) => { switch (action.type) { case 'xxx': default: return state; } } export default {reducer1,reducer2}; import {createStore, combineReducers, applyMiddleware} from 'redux'; import reducer from '../reducers/reducer'; var store = createStore( combineReducers(reducer), //保证store的唯一性,通过combineReducers将多个reducer合并成一个 applyMiddleware(thunk) //redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数,可作为异步操作的一种解决方案 ); export default store; import React from 'react'; import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import route from './js/route/route'; import store from './js/store/store'; store.subscribe(function () { // console.log(store.getState()) //注册listener,store里面state发生改变后,执行该listener }) ReactDOM.render( <Provider store = {store}> //Provider起到获得store,然后将其传递给子孙元素: {route} </Provider>, document.getElementById("app") ) //连接redux import { connect } from 'react-redux'; import actionCreators from '../actions/action'; //引入Action Creator //const action = {}; //action.GET_DATA_START = (state) => { // return { state, type: 'GET_DATA_START' }; //} //export default action class Index extends Component{ constructor(props) { super(props); this.state = this.props.state; //这个state就是reducer1中的state let {GET_DATA_START} = this.props; //GET_DATA_START 就是actionCreators中的方法 GET_DATA_START(state); //调用方法,发送action更新state,render渲染 } render(){ return( ) } } export default connect((state) => { return { state: state.reducer1 }, actionCreators)(Index) //state.reducer1 获取reducer1中的state数据 //被 connect 过的Index 中的 this.props 有了 dispatch 属性。
    转载请注明原文地址: https://ju.6miu.com/read-1000321.html

    最新回复(0)