当我试图访问react组件中的存储时,@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
现在我想从我的商店访问一个数据点,这是什么样子,如果我试图在一个react组件中使用@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() {...}
}
有什么见解或工作流模式吗?
你可以根据我如何访问非反应组件的商店使用中间件?:
中间件
function myServiceMiddleware(myService) {
return ({ dispatch, getState }) => next => action => {
if (action.type == 'SOMETHING_SPECIAL') {
myService.doSomething(getState());
myService.doSomethingElse().then(result => dispatch({ type: 'SOMETHING_ELSE', result }))
}
return next(action);
}
}
使用
import { createStore, applyMiddleware } from 'redux'
const serviceMiddleware = myServiceMiddleware(myService)
const store = createStore(reducer, applyMiddleware(serviceMiddleware))
进一步阅读:Redux Docs >中间件
找到解决办法了。所以我在我的api util中导入store并在那里订阅它。在侦听器函数中,我用新获取的令牌设置了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
也许它可以进一步改进,因为目前它似乎有点不优雅。我以后可以做的是向我的商店添加一个中间件,然后在那里设置令牌。
我也遇到过类似的问题——我想建立一个全局Axios配置,可以从React内部的任何地方访问(组件,组件外部,thunk action内部..)
我最终编写了一个返回配置对象的thunk。好处是,由于getState(),坦克可以访问存储,所以您不必重新发明轮子。也许这个解决方案可以帮助某些人;)
1. 铛
export const getAxiosConfig = (payload) => {
return (dispatch, getState) => {
const { app } = getState();
const axiosConfig: AxiosRequestConfig = {
baseURL: `${process.env.BACKEND_API}`,
headers: {
Authorization: `Bearer ${app.token}`
}
};
return axiosConfig;
}
}
2. 获取配置
const axiosConfig = dispatch(getAxiosConfig(null));
3.使用config调用API
const {data} = await axios.get(/resource/${resourceId},
axiosConfig
);