gpt4 book ai didi

javascript - React-Redux Action 创建器在 props 上不可用

转载 作者:行者123 更新时间:2023-12-03 02:49:30 25 4
gpt4 key购买 nike

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

Uncaught TypeError: Cannot read property 'createTransferSource' of undefined

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

这是我的组件

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);

来 self 的 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
});
});
};
};

最佳答案

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

您可以通过多种方式做到这一点:

方法一:
使用箭头功能

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

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

constructor(props) {
super(props);

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

方法三:
直接在引用 handleOnSuccess 的位置进行绑定(bind)。

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>
);
}

关于javascript - React-Redux Action 创建器在 props 上不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com