Javascript 反应重定向/路由器
我向你提出我的问题 我用下面的代码付款 我想,如果付款被拒绝,我重定向到一个页面,否则,如果付款被接受,我重定向到另一个页面 你知道怎么做吗 我试图简化代码,使其尽可能清晰 谢谢你的帮助,内夫Javascript 反应重定向/路由器,javascript,reactjs,routing,routes,Javascript,Reactjs,Routing,Routes,我向你提出我的问题 我用下面的代码付款 我想,如果付款被拒绝,我重定向到一个页面,否则,如果付款被接受,我重定向到另一个页面 你知道怎么做吗 我试图简化代码,使其尽可能清晰 谢谢你的帮助,内夫 import { Redirect } from 'react-router-dom'; import React, { Component } from 'react'; import { CardNumberElement, CardExpiryElement, CardCVCElement,
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))
从'react router dom'导入{Redirect};
从“React”导入React,{Component};
从'react-
条纹元素';
从“reactstrap”导入{CardText,Col,Container,CardTitle,Button,Input,Card};
导入“./Payment.scss”
const entrypoint=process.env.REACT_APP_API_entrypoint+'/API';
类的形式扩展了组件{
建造师(道具){
超级(道具);
此.state={
警报消息:“”,
警报样式:“”,
randomID:null,
重定向:false,
加载:false,
};
}
handleChange=(e)=>{
this.setState({[e.target.name]:e.target.value});
}
postbackend=()=>{
const newItems=this.props.items.map((item)=>{
常量{标题,数量,}=项目;
返回{
标题
量
};
});
常量配置={
方法:“张贴”,
标题:{
“内容类型”:“应用程序/json”,
},
body:JSON.stringify({…this.state,items:newItems}),
};
const url=entrypoint+“/alluserpls”;
获取(url,配置)
.then(res=>res.json())
。然后(res=>{
if(res.error){
警报(res.error);
}否则{
警报(`film ajoutéavec l'ID${res}!`);
}
}).catch(e=>{
控制台错误(e);
}).finally(()=>this.setState({redirect:true}));
}
handleSubmit=异步(ev)=>{
ev.preventDefault();
this.setState({loading:true});
this.props.stripe.createToken({name:this.props.clientName})
。然后(结果=>{
if(typeof(result.error)!=‘未定义’){
this.setState({error:result.error.message,成功:“”});
this.postbackend();
}否则{
这个.stripeCreateCharge(result.token,这个.props.totalPrice)。然后(()=>{
this.postbackend();
});
}
});
}
StripeCreate费用(代币、金额){
const params={token:token.id,amount:amount};
const qParams=queryString.stringify(params);
常量url=[entrypoint+“/stripe”,qParams].join(“?”);
返回获取(url)
.then(response=>response.json())
.然后(val=>{
如果(val.ok){
返回val.message;
}否则{
抛出val.message;
}
})
。然后(成功=>{
this.setState({alertMessage:success,alertStyle:'success'});
返回承诺。解决()
})
.catch(error=>this.setState({alertMessage:error,alertStyle:'danger'}));
}
render(){
const{loading}=this.state;
const redirect=this.state.redirect;
如果(重定向){
返回
}
否则{
返回(
此.handleSubmit(ev)}>
您的名字叫什么名字
{/*
{!正在加载&&
付款人
{这个.道具.总数}€
}
{加载&&}
)}
)
};
}
}
常量mapStateToProps=(状态)=>{
返回{
项目:state.addedItems,
}
}
导出默认连接(mapStateToProps)(injectStripe(_Form))
在您的postbend
功能中,您可以像这样更新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
部件将处理来自服务器的不成功响应。嗨,伙计,ty需要帮助,我收到了未经处理的拒绝错误(TypeError):无法从react router dom读取未定义的属性“replace”将withRouter hoc中的组件包装为具有历史记录访问权限<代码>使用路由器导出默认值(connect(MapStateTops)(injectStripe(_Form))