react-redux动作创建者在道具上不可用

时间:2017-12-23 04:03:55

标签: javascript reactjs react-redux plaid

我正在尝试使用react-plaid-link将plaid集成到我的应用中。一切正常,直到我执行handleOnSuccess回调。我收到以下错误消息:

  

未捕获的TypeError:无法读取未定义的属性“createTransferSource”

出于某种原因,当我调用handleOnSuccess时,从“../../actions”导出的动作创建者不可用

这是我的组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PlaidLink from 'react-plaid-link';
import * as actions from '../../actions';

const plaidPublicKey = process.env.REACT_APP_PLAID_PUBLIC_KEY;

class PlaidAuthComponent extends Component {

  handleOnSuccess(token, metadata) {
    // send token to client server
    this.props.createTransferSource(metadata);  
  }

  render() {
    return (
      <div>
        <PlaidLink
          publicKey={`${plaidPublicKey}`}
          product="auth"
          env="sandbox"
          clientName="plaidname"
          onSuccess={this.handleOnSuccess}
          />
      </div>
    );
  }
}

export default connect(null, actions )(PlaidAuthComponent);

来自我的actions文件夹中的index.js文件

export * from './transfer_actions';

我的transfer_actions.js文件

export const createTransferSource = (values, callback) => {
  return function (dispatch){

  axios({
    method : 'POST',
    url: `xxx/transfer_source.json`, 
    data: { values } 
  })
    .then(response => {
      dispatch({ 
        type: CREATE_TRANSFER_SOURCE,
        payload: response
      });
    })
    .then(() => callback())
    .catch( error => {
    dispatch({
      type: CREATE_TRANSFER_SOURCE_ERROR,
      payload: error.response
    });
    });
  };
};

3 个答案:

答案 0 :(得分:0)

我在这里找到了答案:https://github.com/reactjs/react-redux/issues/328

我添加了以下代码

  constructor(props){
    super(props);
    this.handleOnSuccess = this.handleOnSuccess.bind(this); 
  }

答案 1 :(得分:0)

你可以这样写handleOnSuccess

handleOnSuccess = (token, metadata) => {
  this.props.createTransferSource(metadata);
}

这样您就可以保留this上下文,而不需要绑定的构造函数。

答案 2 :(得分:0)

您需要绑定this否则会在组件中丢失它。

您可以通过多种方式实现这一目标:

方法一:
使用箭头功能

handleOnSuccess = (token, metadata) => {
  this.props.createTransferSource(metadata);
}

方法二:
绑定在构造函数中。

constructor(props) {
   super(props);

   this.handleOnSuccess = this.handleOnSuccess.bind(this); 
}

方法三:
直接绑定引用handleOnSuccess的位置。

render() {
    return (
      <div>
        <PlaidLink
          publicKey={`${plaidPublicKey}`}
          product="auth"
          env="sandbox"
          clientName="plaidname"
          onSuccess={this.handleOnSuccess.bind(this)}
          />
      </div>
   );
}

方法四:
使用箭头函数调用handleOnSuccess引用

render() {
    return (
      <div>
        <PlaidLink
          publicKey={`${plaidPublicKey}`}
          product="auth"
          env="sandbox"
          clientName="plaidname"
          onSuccess={() => this.handleOnSuccess}
          />
      </div>
   );
}