如何最好地在React组件外部访问Redux Store?
如何最好地在React组件外部访问Redux Store?
@connect
在我尝试在 react 组件内访问 store 时表现得非常出色。但是我应该如何在其他代码中访问它呢?例如:假设我想使用授权令牌来创建 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
现在我想访问 store 中的一个数据点,如果我正在使用 @connect
在 react 组件内获取它,那么它应该如何显示:
// 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() {...} }
有没有什么见解或工作流程模式可以分享?
admin 更改状态以发布 2023年5月24日
找到了解决方法。所以我在我的 api util 中导入了 store,并在那里订阅了它。在该监听函数中,我使用新获取的 token 设置了 axios 的全局默认值。
这是我的新 api.js
的样子:
// tooling modules import axios from 'axios' // store import store from '../store' store.subscribe(listener) function select(state) { return state.auth.tokens.authentication_token } function listener() { let token = select(store.getState()) axios.defaults.headers.common['Authorization'] = token; } // configuration const api = axios.create({ baseURL: 'http://localhost:5001/api/v1', headers: { 'Content-Type': 'application/json', } }) export default api
也许它可以进一步改进,因为目前它看起来有点不雅。我可以稍后添加一个中间件到我的存储中,并在那里设置 token。
从你调用createStore
的模块中导出存储库。这样你就有保证了,它既会被创建,也不会污染全局窗口空间。
MyStore.js
const store = createStore(myReducer); export store;
或者
const store = createStore(myReducer); export default store;
MyClient.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')