将redux-token-auth函数提升到视图之外的动作文件?

时间:2018-05-22 16:55:00

标签: reactjs authentication redux react-redux redux-thunk

使用redux-token-auth寻找指导。抛出此类型错误:

Error

所有创作者'示例涉及从Component类进行调用,如下所示:

// EXAMPLE: components/SignInScreen.jsx
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { signInUser } from '../redux-token-auth-config' // <-- note this is YOUR file, not the redux-token-auth NPM module

class SignInScreen extends Component {
  constructor (props) { ... }

  ...

  submitForm (e) {
    e.preventDefault()
    const { signInUser } = this.props
    const {
      email,
      password,
    } = this.state
    signInUser({ email, password }) // <-<-<-<-<- here's the important part <-<-<-<-<-
      .then(...)
      .catch(...)
  }

  render () {
    const { submitForm } = this
    <div>
      <form onSubmit={submitForm}>...</form>
    </div>
  }
}

export default connect(
  null,
  { signInUser },
)(SignInScreen)

将呼叫转移到动作文件是否可行?在文档中,他提到了

  

registerUser,signInUser和signOutUser是Redux Thunk动作和   因此,当通过mapDispatchToProps连接时返回Promises。

我正在深入挖掘源代码,但我无法弄清楚当通过Redux映射签名时的更改,而不是直接导入和调用。如果有人熟悉这个扩展,任何想法将不胜感激!

这是我尝试抛出错误:

// /actions/auth.js
import { signInUser, signOutUser } from '../redux-token-auth-config'

export const Login = (email, password) => {
    return (dispatch) => {
        dispatch(LoginStart());
        signInUser({ email, password })
            .then((response) => dispatch(LoginSuccess(response.data.data)))
            .catch((error) => dispatch(LoginError(error)));
    };
};

export const LoginStart = () => ({
    type: 'LOGIN::START'
});

export const LoginSuccess = (data) => ({
    type: 'LOGIN::SUCCESS',
    payload: data
});

export const LoginError = (error) => ({
    type: 'LOGIN::ERROR',
    payload: error
})

export const Logout = () => {
    return (dispatch) => {
        dispatch(SessionCleanup())
        signOutUser()
            .then((response) => console.log('Success'))
            .catch((error) => console.log(error))
    }
}

export const SessionCleanup = () => ({
    type: 'LOGIN::SESSION_CLEANUP'
})

1 个答案:

答案 0 :(得分:0)

假设您正尝试从具有相同问题的组件中调用Login,并通过以下操作对其进行了修复:

export default connect(state => ({}), { signInUser })(FooBar);

当我打电话给我时,我通过了signInUser

this.props.fooBarBaz(email, password, signInUser);

这使我可以像在组件外一样在组件外使用signInUser

因此,在您的情况下,它应该像保存一样简单:

export default connect(
  null,
  { signInUser },
)(SignInScreen)

并像这样呼叫Login

Login(email, password, signInUser);