【发布时间】:2016-11-22 11:47:28
【问题描述】:
@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 在 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() {...}
}
有任何见解或工作流程模式吗?
【问题讨论】:
-
你不希望你的 Axios 实例存在于 redux 中间件中吗?通过这种方式,您的所有应用程序都可以使用它
-
你可以在
App类中导入api,得到授权令牌后你可以做api.defaults.headers.common['Authorization'] = this.props.auth.tokens.authorization_token;,同时你也可以把它存储在localStorage中,所以当用户刷新页面,可以查看localStorage中是否存在token,如果存在,可以设置,我觉得最好一拿到就在api模块上设置token。 -
Dan Abromov 在此处的问题队列中提供了一个示例:github.com/reactjs/redux/issues/916
-
如果你只需要从特定的reducer访问特定的状态,你可以试试redux-named-reducers它允许你从任何地方访问最新的状态。
标签: reactjs redux react-redux