在反应组件之外访问 redux 存储的最佳方法是什么?

新手上路,请多包涵

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

这是我的 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 在反应组件中获取它,这会是什么样子

// 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() {...}
}

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

原文由 Subodh Pareek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 381
1 个回答

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

我的商店.js

 const store = createStore(myReducer);
export store;

要么

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

我的客户端.js

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

或者如果你使用 默认

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

对于多个商店用例

如果您需要一个商店的多个实例,请导出一个工厂函数。我建议制作它 async (返回 promise )。

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

在客户端(在 async 块中)

 import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

原文由 Steven Spungin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进