react-redux

react-redux 相關(guān)步驟

  • npm install react-redux --save 在項(xiàng)目中導(dǎo)入react-rudux包
  • 創(chuàng)建reducer文件
const LOGIN_IN = '登陸';

// 創(chuàng)建一個(gè)reducer對(duì)象
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函數(shù)
export function login(){
    return {type:LOGIN_IN}
}



  • 多個(gè)reducer對(duì)象的合并

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';
// 創(chuàng)建store對(duì)象
const store = createStore(reducers);
// 組建中用provider包住
ReactDOM.render(

    (
        <Provider store={store}>
            <TodoList />
        </Provider>
    ),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 (
            <div>
                <h1>{this.props.state.app}</h1>
// dispatch 一個(gè)action
                <button onClick={this.props.add}>增加</button>
                <button onClick={this.props.sub}>減少</button>
                <button onClick={()=>this.logAllData()}>打印數(shù)據(jù)</button>
                <h1>{this.props.state.auth.name}</h1>
                <button onClick={this.props.login}>登陸</button>
            </div>
        );
    }

    logAllData(){
        console.log('jjjjj')
        console.log(this.props.state)
    }

}


// store,action 之間的建立聯(lián)系
App = connect(maptostate,maptoaction)(App)

export default App;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容