反应 Redirect/Router

React Redirect/Router

我向你提出我的问题

我用下面的代码付款,

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

你知道怎么做吗?

我尽量简化代码,让它尽可能清晰

感谢内夫的帮助

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

在您的 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 部分将处理来自服务器的不成功响应。