react-redux

react-redux 相关步骤

  • npm install react-redux --save 在项目中导入react-rudux包
  • 创建reducer文件
const LOGIN_IN = '登陆';

// 创建一个reducer对象
export function auth(state={isAuth:false,name:'dan'},action){
    switch (action.type){
        case LOGIN_IN:
            return {...state,isAuth:true,name:'lidazhou'}
            break;
        default:
            return state;
            break;
    }
}


// action函数
export function login(){
    return {type:LOGIN_IN}
}



  • 多个reducer对象的合并

import { combineReducers } from 'redux';

import {app} from './app.redux';
import { auth} from './Auth.redux';
import {list } from './todo.redux'

export default combineReducers({app,auth,list})

  • 在index.js中,引入Provider,reducers,createStore
import {Provider} from 'react-redux';
import reducers from './reducers';
import {createStore} from 'redux';
// 创建store对象
const store = createStore(reducers);
// 组建中用provider包住
ReactDOM.render(

    (
        
            
        
    ),document.getElementById('root'));
  • 在组件中的使用
import { connect } from 'react-redux';
import {add,sub} from './app.redux';
import {login} from './Auth.redux'

// 将store中的值state传入到组件的props中
const maptostate = (state) =>{
    return ({state:state})
}

// 将reducers中的方法传入到组件的props中
const maptoaction = {add,sub,login};

 class App extends Component {

    constructor(props){
        super(props);
       
    }

    render() {
        // const store = this.props.store;

        return (
            

{this.props.state.app}

// dispatch 一个action

{this.props.state.auth.name}

); } logAllData(){ console.log('jjjjj') console.log(this.props.state) } } // store,action 之间的建立联系 App = connect(maptostate,maptoaction)(App) export default App;

你可能感兴趣的:(react-redux)