【问题标题】:React Stripe - Map State to Props on a stripe injected component?React Stripe - 将状态映射到条带注入组件上的道具?
【发布时间】:2021-02-28 21:57:09
【问题描述】:

我正在尝试将我的 redux 商店连接到我的 CheckoutForm,我已经按照条形文档进行了响应设置。我希望能够访问 redux 和调度项目,但我不确定如何继续。如何连接下面的代码?

CheckoutForm.js

...
   render() {

      const {stripe} = this.props;
      const {postal, name, paymentMethod, errorMessage} = this.state;

      return (
        <div>
          { this.state.showPay ? 

          <button onClick={this.payWithCard}>
            Pay with stored card
          </button>
          :
          <form onSubmit={this.SaveCard}>
            <CardSection />
          <button>Save Card</button>
          </form>
          }
        </div>
        
      );
    }
  }

  export default function InjectedCheckoutForm() {
    return (
      <ElementsConsumer>
        {({ stripe, elements }) => (
          <CheckoutForm stripe={stripe} elements={elements} />
        )}
      </ElementsConsumer>
    );
  }

通常我会这样做:

const mapStateToProps = (state) => {

    const { reducer } = state
     return { reducer }
   };

   const mapDispachToProps = dispatch => {
     return {
       storePaymentIntent: (y) => dispatch({ type: "PAYMENT_INTENT", value: y })
     };
   };
  
   export default connect(mapStateToProps, mapDispachToProps)(CheckoutForm);

我已经尝试了以下方法,但似乎我只能在初始减速器的值发生变化后才拉动它。

import ourReducer from './store/reducer';
import { createStore } from 'redux';
const store = createStore(ourReducer);
...
console.log(store.getState().reducer); //GIVES ME NULL VALUES*******
  export default function InjectedCheckoutForm() {
    return (
      <ElementsConsumer>
        {({ stripe, elements }) => (
          <CheckoutForm stripe={stripe} elements={elements} />
        )}
      </ElementsConsumer>
    );
  }

  store.subscribe(InjectedCheckoutForm);

【问题讨论】:

  • 我对您拨打store.subscribe(InjectedCheckoutForm) 的要求有点迷茫。一般来说,您只需将 InjectedCheckoutForm 连接到 Redux。如果您愿意,也可以连接 CheckoutForm 本身。从那里您应该能够调度操作,并且组件将自动订阅状态更新。从您共享的代码中,您没有调度任何操作来更新状态,因此预计您返回的值都是null 对吗?
  • 它们是在不同组件中设置的值,因此它们不应该为空。无论哪种方式都可以在下面找到。不过谢谢!

标签: javascript reactjs stripe-payments


【解决方案1】:

想通了。通过执行以下操作,我能够访问 Redux 存储值:

...
   const mapStateToProps = (state) => {
     const { reducer } = state
     return { reducer }
   };
   
   const mapDispachToProps = dispatch => {
     return {
       storePaymentIntent: (y) => dispatch({ type: "PAYMENT_INTENT", value: y })
     };
   };

   const InjectedCheckoutForm = (props) => (
    <ElementsConsumer>
        {({ stripe, elements }) => (
            <CheckoutForm 
            stripe={stripe} elements={elements}  {...props}
            />
        )}
    </ElementsConsumer>
  );
  
  export default connect(mapStateToProps, mapDispachToProps)(InjectedCheckoutForm);

   

【讨论】:

  • 你先生是救生员
猜你喜欢
  • 2017-11-07
  • 2016-02-29
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多