美文网首页
在react中全局使用redux

在react中全局使用redux

作者: _duck不必 | 来源:发表于2018-11-01 18:02 被阅读0次

在之前的项目中用到了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的数据状态
//执行事件

window.$store.dispatch({type:"test",text:"我是test事件传递的数据"})

教程简陋,有什么不明白的可以在评论提问

以上。

相关文章

网友评论

      本文标题:在react中全局使用redux

      本文链接:https://www.haomeiwen.com/subject/ztgxxqtx.html