Redux中的Axios Action不是“可以”的

时间:2017-05-18 07:42:31

标签: javascript reactjs react-redux axios redux-thunk

我有一个与Redux完全一致的React设置。在我的操作文件中,我使用axios来调用第三方API。

将我的表单组件连接到Redux存储并尝试调用POST操作后,我遇到一个错误,说我无法调用未定义的...有趣的是该操作仍被调用,即表单是在抛出此控制台错误后立即提交给第三方的api。 我看过很多S / O问题以及axios& amp; redux-thunk docs,但看不出我错过了什么。以下是一些相关代码:

actions.js

import axios from 'axios';
import _ from 'lodash'
import runtimeEnv from '@mars/heroku-js-runtime-env';
import {apiErrorCatcher} from "../../../utils/errorCatcher"
import {toastr} from 'react-redux-toastr'

const env = runtimeEnv();

export function createProfile(data) {
    return dispatch => {
        axios.post( env.REACT_APP_API_URL  + '/api/profile/', data).then( 
            (res) => {
                toastr.success('Profile added', 'Congratulations on adding your profile')
                return res
            }
        )
        .catch(function (error) {
            apiErrorCatcher(error)
            toastr.error('Oops...', 'Unfortunately an error occurred on our side. Please try again later.')
            return error
        })
    }
}

Profile.js

...

handleCreateProfile=()=>{
  this.props.actions.createProfile(this.state.data).then( 
    (res) => {console.log(res)}
  )
}

...

function mapDispatchToProps(dispatch) {
    return { actions: bindActionCreators({createProfile}, dispatch) }
}


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Profile))

index.js

...
const store = createStore(
  rootReducer,
  composeWithDevTools(
    applyMiddleware(thunk, oidcMiddleware)
  )
);

...
ReactDOM.render(
    <Provider store={store}>
      <OidcProvider store={store} userManager={userManager}>
        <BrowserRouter>
          <MuiThemeProvider>
            <App />
          </MuiThemeProvider>
        </BrowserRouter>
      </OidcProvider>
    </Provider>,
  document.getElementById('root')
);

我认为错误可能与承诺有关,但我并非100%自信。也不知道如何解决这个问题,因为我无法看到我出错的地方。

1 个答案:

答案 0 :(得分:0)

问题在于您的组件方法:

this.props.actions.createProfile(this.state.data).then( 
  (res) => {console.log(res)}
)

因为行动不会返回承诺,所以如果您想要记录您的数据或发送行动,您应该在行动中执行createProfile。