Redux加载状态异步并与axios一起使用

时间:2018-05-06 11:32:20

标签: javascript reactjs redux axios

我是React和Redux的新手,目前我正在研究React项目,并对Redux集成有一些疑问。

1。异步加载状态

我有index.js个文件,它是我项目的入口点:

import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <App />
    </Router>
  </Provider>,
  document.getElementById('root')
)

我在这里导入store.js

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers'

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
)

export default store

App.js

import React, { Component } from 'react'
import { Route } from 'react-router-dom'
import UserRoute from './components/UserRoute'
import GuestRoute from './components/GuestRoute'
import Menu from './components/Menu'
import LoginPage from './components/pages/LoginPage'
import SignupPage from './components/pages/SignupPage'
import HomePage from './components/pages/HomePage'
import ProfilePage from './components/pages/ProfilePage'
import GroupsPage from './components/pages/GroupsPage'


class App extends Component {
  render() {
    return (
      <div>
        <Menu />
        <Route exact path="/" component={HomePage} />
        <GuestRoute exact path="/login" component={LoginPage} />
        <GuestRoute exact path="/signup" component={SignupPage} />
        <UserRoute exact path="/profile" component={ProfilePage} />
        <UserRoute exact path="/groups" component={GroupsPage} />
      </div>
    )
  }
}

export default App

我剪了一些代码,让它更具可读性。请注意UserRouteGuestRoute个组件。 UserRoute仅允许经过身份验证的用户导航到该页面,而GuestRoute则相反。我在localStorage中保存了用户令牌,然后我用它从服务器获取用户数据。我想在渲染App组件之前得到响应。如果我不等待回复且我的位置为/profile,那么UserRoute会将我重定向到主页面。为了避免重定向,我可以这样做:

getState().then(() => {
  ReactDOM.render(
    <Provider store={store}>
      <Router>
        <App />
      </Router>
    </Provider>,
    document.getElementById('root')
  )
})

但是在渲染之前加载状态是好方法吗?或者还有其他更好的&#34;如何做到这一点?

2。在其他文件中导入商店

如何在axios请求中获取当前状态?可以在store.js中导出商店,然后将其导入api.js文件:

import axios from 'axios'
import store from './store'

const client = axios.create({
  baseURL: 'http://localhost:3001',
  headers: { 'Content-type': 'application/json' }
})

// Used to set current JWT token(part of third question)
export function setAuthorizationHeader(token = '') {
  if (token) {
    client.defaults.headers.common['Authorization'] = `Bearer ${token}`
  } else {
    delete client.defaults.headers.common['Authorization']
  }
}

export default {
  user: {
    fetch() {
      return client.get('/user').then(res => res.data)
    },
    // other api calls which use current state of store
  }
}

3。不是纯粹的动作创作者

这个问题是关于行动的创造者。我有以下行动创作者:

import api, { setAuthorizationHeader } from '../api'

export function setUser(user) {
  return { type: 'SET_USER', user }
}
export function setUserToken(token) {
  return { type: 'SET_USER_TOKEN', token }
}
export const login = credentials => async dispatch => {
  const { user, token } = await api.user.login(credentials)
  // TODO: refactor this
  setAuthorizationHeader(token)

  dispatch(setUserToken(token))
  dispatch(setUser(user))
}

当我从服务器得到响应时,我为axios客户端设置了Authorization标头。它们不是纯函数吗?

此外,您可以查看我的{{3}},以便更好地了解代码的工作原理。

0 个答案:

没有答案