javascript - react : Updating Component Property

标签 javascript reactjs properties components plotly-dash

好吧,我正式花了几个小时试图解决这个问题,但我确信这是一个简单的修复。我是 React 的新手,正在尝试为 Plotly Dash 创建自定义组件。

问题

我正在尝试更新 LoginForm 组件的 token 属性,该组件使用熟悉的 Plaid 链接。您会在 LoginForm.react.jshandleOnSuccess 函数中注意到我能够检索 token 并将其显示在控制台中。我想要做的就是用控制台中显示的值更新 LoginFormtoken 属性。

下面是整个LoginForm.react.js:

import React, { Component } from 'react';
import Script from 'react-load-script';
import PropTypes from 'prop-types';


class LoginForm extends Component {
    constructor(props) {
        super(props);

        this.state = {
            linkLoaded: false,
            initializeURL: 'https://cdn.plaid.com/link/v2/stable/link-initialize.js',
        };

        this.onScriptError = this.onScriptError.bind(this);
        this.onScriptLoaded = this.onScriptLoaded.bind(this);

        this.handleLinkOnLoad = this.handleLinkOnLoad.bind(this);

        this.handleOnExit = this.handleOnExit.bind(this);
        this.handleOnEvent = this.handleOnEvent.bind(this);
        this.handleOnSuccess = this.handleOnSuccess.bind(this);

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

    onScriptError() {
        console.error('There was an issue loading the link-initialize.js script');
    }

    onScriptLoaded() {
        window.linkHandler = window.Plaid.create({
            apiVersion: this.props.apiVersion,
            clientName: this.props.clientName,
            env: this.props.env,
            key: this.props.publicKey,
            onExit: this.handleOnExit,
            onLoad: this.handleLinkOnLoad,
            onEvent: this.handleOnEvent,
            onSuccess: this.handleOnSuccess,
            product: this.props.product,
            selectAccount: this.props.selectAccount,
            token: this.props.token,
            webhook: this.props.webhook,
        });

        console.log("Script loaded");
    }

    handleLinkOnLoad() {
        console.log("loaded");
        this.setState({ linkLoaded: true });
    }
    handleOnSuccess(token, metadata) {
        console.log(token);
        console.log(metadata);
    }
    handleOnExit(error, metadata) {
        console.log('link: user exited');
        console.log(error, metadata);
    }
    handleOnLoad() {
        console.log('link: loaded');
    }
    handleOnEvent(eventname, metadata) {
        console.log('link: user event', eventname, metadata);
    }

    renderWindow() {
        const institution = this.props.institution || null;
        if (window.linkHandler) {
            window.linkHandler.open(institution);
        }
    }

    static exit(configurationObject) {
        if (window.linkHandler) {
            window.linkHandler.exit(configurationObject);
        }
    }

    render() {
        return (
            <div id={this.props.id}>
                {this.renderWindow()}
                <Script
                    url={this.state.initializeURL}
                    onError={this.onScriptError}
                    onLoad={this.onScriptLoaded}
                />
            </div>
        );
    }
}

LoginForm.defaultProps = {
    apiVersion: 'v2',
    env: 'sandbox',
    institution: null,
    selectAccount: false,
    style: {
        padding: '6px 4px',
        outline: 'none',
        background: '#FFFFFF',
        border: '2px solid #F1F1F1',
        borderRadius: '4px',
    },
};

LoginForm.propTypes = {
    // id
    id: PropTypes.string,

    // ApiVersion flag to use new version of Plaid API
    apiVersion: PropTypes.string,

    // Displayed once a user has successfully linked their account
    clientName: PropTypes.string.isRequired,

    // The Plaid API environment on which to create user accounts.
    // For development and testing, use tartan. For production, use production
    env: PropTypes.oneOf(['tartan', 'sandbox', 'development', 'production']).isRequired,

    // Open link to a specific institution, for a more custom solution
    institution: PropTypes.string,

    // The public_key associated with your account; available from
    // the Plaid dashboard (https://dashboard.plaid.com)
    publicKey: PropTypes.string.isRequired,

    // The Plaid products you wish to use, an array containing some of connect,
    // auth, identity, income, transactions, assets
    product: PropTypes.arrayOf(
        PropTypes.oneOf([
            // legacy product names
            'connect',
            'info',
            // normal product names
            'auth',
            'identity',
            'income',
            'transactions',
            'assets',
        ])
    ).isRequired,

    // Specify an existing user's public token to launch Link in update mode.
    // This will cause Link to open directly to the authentication step for
    // that user's institution.
    token: PropTypes.string,

    // Set to true to launch Link with the 'Select Account' pane enabled.
    // Allows users to select an individual account once they've authenticated
    selectAccount: PropTypes.bool,

    // Specify a webhook to associate with a user.
    webhook: PropTypes.string,

    // A function that is called when a user has successfully onboarded their
    // account. The function should expect two arguments, the public_key and a
    // metadata object
    onSuccess: PropTypes.func,

    // A function that is called when a user has specifically exited Link flow
    onExit: PropTypes.func,

    // A function that is called when the Link module has finished loading.
    // Calls to plaidLinkHandler.open() prior to the onLoad callback will be
    // delayed until the module is fully loaded.
    onLoad: PropTypes.func,

    // A function that is called during a user's flow in Link.
    // See
    onEvent: PropTypes.func,

    // Button Styles as an Object
    style: PropTypes.object,

    // Button Class names as a String
    className: PropTypes.string,
};

export default LoginForm;

这里是 App.js:

// /* eslint no-magic-numbers: 0 */
import React, { Component } from 'react';
import { LoginForm } from '../lib';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            token: null
        }
    }

    render() {
        return (
            <LoginForm
                id="Test"
                clientName="Plaid Client"
                env="sandbox"
                product={['auth', 'transactions']}
                publicKey="7a3daf1db208b7d1fe65850572eeb1"
                className="some-class-name"
                apiVersion="v2"
                token={this.state.token}
            >
            </LoginForm>
        );
    }
}

export default App;

我认为必须防止将任何函数分配给 LoginForm 的属性,即 token={this.someFunction} 是 Not Acceptable

我也知道直接更改属性的值是不可取的(如果可能的话),即逻辑上将 this.props.token=token 插入 handleOnSuccess 函数可能有效(从逻辑上讲——我知道它不起作用),但它仍然没有真正提供父进程和子进程之间更新组件的良好流程。

我感谢所有帮助,因为这实际上是这个小项目的最后一步,我真的想不通。提前致谢!

如果这样更容易 - 您可以在此处克隆存储库:https://github.com/SterlingButters/plaidash

最佳答案

您可以在 App 中使用 handleUpdateToken 方法,将其作为 prop 传递给 LoginForm:

class App extends Component {
  ...
  handleUpdateToken(token) {
    this.setState({ token });
  }

  ...
  render() {
    return (
      <LoginForm
        onUpdateToken={this.handleUpdateToken}
        ...other LoginForm props
      />
  }
}

在登录表单中:

handleOnSuccess(token, metadata) {
  console.log(token);
  console.log(metadata);
  this.props.onUpdateToken(token);
}

关于javascript - react : Updating Component Property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603222/

相关文章:

reactjs - React 如何使用 useState 和 useContext 将状态值从子级更改为父级

javascript - 如何在 React.js 中将文本的一部分加粗?

java - 获取和设置键值属性

java.lang.NoClassDefFoundError : android. support.v4.content.LocalBroadcastManager facebook android 应用程序

objective-c - Objective-c 中 SEL 类型的属性

javascript - 仅当鼠标位于 div 上时,Jquery 在悬停时处于事件状态

javascript - 使用纯js将具有子级和孙级子级的整个元素附加到另一个元素

javascript - 谷歌脚本上的“数据验证规则限制为 500”错误

database - 如何从reactjs发出Http请求?

javascript - 在 jQuery 淡入中使用 'this' 变量?