在 React 组件之外访问 redux 存储的最佳方式是什么? [英] What is the best way to access redux store outside a react component?

查看:44
本文介绍了在 React 组件之外访问 redux 存储的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@connect 在我尝试访问 React 组件中的商店时效果很好.但是我应该如何在其他一些代码中访问它.例如:假设我想使用授权令牌来创建可在我的应用程序中全局使用的 axios 实例,实现这一目标的最佳方法是什么?

@connect works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?

这是我的api.js

// tooling modules
import axios from 'axios'

// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'

export default api

现在我想从我的商店访问一个数据点,如果我尝试使用 @connect

Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect

// connect to store
@connect((store) => {
  return {
    auth: store.auth
  }
})
export default class App extends Component {
  componentWillMount() {
    // this is how I would get it in my react component
    console.log(this.props.auth.tokens.authorization_token) 
  }
  render() {...}
}

有任何见解或工作流程模式吗?

Any insights or workflow patterns out there?

推荐答案

从您调用 createStore 的模块中导出商店.那么你可以放心,它既会被创建,也不会污染全局窗口空间.

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

const store = createStore(myReducer);
export store;

const store = createStore(myReducer);
export default store;

MyClient.js

import {store} from './MyStore'
store.dispatch(...)

或者如果你使用了default

import store from './MyStore'
store.dispatch(...)

对于多个商店用例

如果你需要一个 store 的多个实例,导出一个工厂函数.我建议让它async(返回一个promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
}
export getUserStore

在客户端(在 async 块中)

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

这篇关于在 React 组件之外访问 redux 存储的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆