在react中全局使用redux

在之前的項目中用到了react
因為之前也用到了全局變量,了解到了redux
但是受vuex的影響,一直想把redux在全局中使用,便把store綁到了window上

redux.js

import { createStore } from 'redux';
const initialState = {
  str:"hello word"
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case "test":
          console.log(action)

        default:
            return initialState;
    }
}
let store = createStore(reducer);
window.$store = store;

然后在App.js中引入redux.js

在index.js中

import "./redux/redux.js"

接下來就可以在全局中使用啦

在任意js中

window.$store.getState()   //可以直接獲取到當前的initialState的數(shù)據(jù)狀態(tài)
//執(zhí)行事件

window.$store.dispatch({type:"test",text:"我是test事件傳遞的數(shù)據(jù)"})

教程簡陋,有什么不明白的可以在評論提問

以上。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容