小编Sub*_*eek的帖子

在反应组件外部访问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
Run Code Online (Sandbox Code Playgroud)

现在我想从我的商店访问一个数据点,如果我试图在反应组件中使用它来获取它,那么这就是 @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() {...}
}
Run Code Online (Sandbox Code Playgroud)

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

reactjs redux react-redux

163
推荐指数
9
解决办法
9万
查看次数

标签 统计

react-redux ×1

reactjs ×1

redux ×1