Redirect Redirect / Router

问题描述 投票:0回答:1

我向您介绍我的问题

[使用以下代码我付款,

我希望如果付款被拒绝,我将重定向到一个页面,否则,如果付款被接受,我将重定向到另一个页面

您知道如何执行此操作吗?

我试图简化代码,使其尽可能清晰

感谢您的帮助Neff

 import { Redirect } from 'react-router-dom';

 import React, { Component } from 'react';
 import { CardNumberElement, CardExpiryElement, CardCVCElement, injectStripe } from 'react- 
 stripe-elements';
 import { CardText, Col, Container, CardTitle, Button, Input, Card } from 'reactstrap';
 import './Payment.scss'


 const entrypoint = process.env.REACT_APP_API_ENTRYPOINT + '/api';

class _Form extends Component {

constructor(props) {
super(props);
this.state = {
  alertMessage: '',
  alertStyle: '',
  randomID: null,
  redirect: false,
  loading: false,
};
}

handleChange = (e) => {

this.setState({ [e.target.name]: e.target.value });
}



postbackend = () => {
 const newItems = this.props.items.map((item) => {
   const { title, quantity, } = item;
   return {
    title,
    quantity,

  };
});
const config = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ ...this.state, items: newItems }),
};

const url = entrypoint + "/alluserpls";
fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`film ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);

    }).finally(() => this.setState({ redirect: true }));
 }

 handleSubmit = async (ev) => {
ev.preventDefault();
this.setState({ loading: true });

this.props.stripe.createToken({ name: this.props.clientName })
  .then(result => {
    if (typeof (result.error) !== 'undefined') {
      this.setState({ error: result.error.message, success: '' });
      this.postbackend();
     } else {
      this.stripeCreateCharge(result.token, this.props.totalPrice).then(() => {
        this.postbackend();
      });
     }
  });
} 

stripeCreateCharge(token, amount) {
const params = { token: token.id, amount: amount };
const qParams = queryString.stringify(params);
const url = [entrypoint + "/stripe", qParams].join('?');

return fetch(url)
  .then(response => response.json())
  .then(val => {
    if (val.ok) {
      return val.message;
    } else {
      throw val.message;
    }
  })
  .then(success => {
    this.setState({ alertMessage: success, alertStyle: 'success' });
    return Promise.resolve()
  })
  .catch(error => this.setState({ alertMessage: error, alertStyle: 'danger' }));
}

render() {

const { loading } = this.state;
const redirect = this.state.redirect;

if (redirect) {
  return <Redirect to="/OderSummaryScreen" />

}
else {
  return (

    <div >
      <form method="post" onSubmit={(ev) => this.handleSubmit(ev)}>
        <Container>
          <CardTitle className='cardTitlePaymentFormComponent'>Entre ton moyen de paiement</CardTitle>

          <Card className="CardPaymenntFormComponenentCard">

            {/* <Alert msg={this.state.alertMessage} style={this.state.alertStyle} /> */}

            <div className="col12PaymentFormComponent">
              <div className="col8PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'>Numéro de Carte</CardText>
                <CardNumberElement className="cardNumberElementPaymentFormComponent" />
              </div>

              <div className="col4PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'> Expiration</CardText>
                <CardExpiryElement className="cardExpiryElementPaymentFormComponent" />
              </div>
            </div>
            <div className="col12PaymentFormComponent">
              <div className="col8PaymentFormComponent">
                <ClienInfo />
              </div>
              <div className="col4PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'>Cryptogramme</CardText>
                <CardCVCElement className="cardCVCElementPaymentFormComponent" />
              </div>
            </div>
          </Card>
        </Container>
                  <Container className='containerPaymentFooterContainer' >
                    <Col sm="12" className='col12PaymentsFooter'>

                      <Input onClick={this.handleClick} type="checkbox" required className="inputCheckboxPaymentsFooter" />{' '}
                      <CardText className='cardTextPaymentsFooter' > <a href="https://brable.io/mentions-legales/" target="blank" className="colorForLinkMaybeBlank"> Je reconnais avoir lu et pris connaissance des Termes, de la Charte de Confidentialité et des CGU, et les accepte.</a></CardText>
                    </Col>
                  </Container>
                  <Col sm="12" className='col12PaymentsFooterButtonCol12' >
                    {!loading && <div >
                      <Button className='buttonPaymentsFooterbutton' type="submit" value="Envoyer" disabled={loading} >
                        <CardTitle className="buttonPaymentsCardTitleFooter">PAYER </CardTitle>
                        <CardTitle className="buttonPaymentsCardTitleFooter" >{this.props.total} €  </CardTitle>
                      </Button>
                    </div>}
                    {loading && <div className="wtfloadingLogoHandeSpinerBro" ><Handespiner /> </div>}
                  </Col>
                </Form>
              )}
            </Formik>
          </Col>

        </Container>
      </form>
    </div>
  )
  };
 }
 }

const mapStateToProps = (state) => {
return {
items: state.addedItems,

 }
 }

 export default connect(mapStateToProps)(injectStripe(_Form))
javascript reactjs routing routes
1个回答
0
投票
postbackend功能中,您可以像这样更新fetch请求:

fetch(url, config) .then(res => res.json()) .then(res => { if (res.error) { alert(res.error); this.props.history.replace("/"); // Your Error Page } else { alert(`film ajouté avec l'ID ${res}!`); this.props.history.push("/"); // Your Success Page } }).catch(e => { console.error(e); this.props.history.replace("/"); // Your Error Page }).finally(() => this.setState({ redirect: true }));

catch情况将在出现任何错误的情况下被调用。尽管您的else部分将处理服务器的不成功响应。
© www.soinside.com 2019 - 2024. All rights reserved.