【问题标题】:React - axios post request with bodyReact - 带有正文的 axios 发布请求
【发布时间】:2021-11-17 16:42:13
【问题描述】:

刚接触并处理带有后端的项目。 到目前为止,我一直在使用带有 GetDeleteGetparams 的 axios。

我对正文的发布请求有点麻烦。 我认为我的语法没问题,但是我的问题是如何根据用户请求获取某些数据。

E.G::网站上有一个优惠券列表,我的后端有一个Get 请求和一个Purchase now 按钮。 我想做的是当authenticated 用户按下按钮时,该特定优惠券将作为post 请求及其正文发送。

我真的不知道该怎么做,因为我真的很陌生。

购买优惠券组件:

interface CustomerState {
    coupons: any;
}

class PurchaseCoupon extends Component <{}, CustomerState, CouponModel> {
    public constructor(props: {}) {
        super(props);
        this.state = {
            coupons: store.getState().couponState.coupons,
        };
    }

    public async componentDidMount() {
        try {
            const response = await axios.post<CouponModel>(globals.urls.purchasedCoupon,
                {
                data: {
                    
                },
                
                });
            store.dispatch(couponPurchasedAction(response.data)); // Updating global state
            this.setState({ coupons: response.data });
        } catch (err) {
            alert(err);
        }
    }


    public render(): JSX.Element {
        return (
            <div className="PurchaseCoupon">
                
            </div>
        );
    }
}

export default PurchaseCoupon;

优惠券列表组件:

interface CouponListState {

    coupons: CouponModel[];

}

class CouponList extends Component<{}, CouponListState>{

    public constructor(props: {}) {
        super(props);
        this.state = {
            coupons: store.getState().couponState.coupons,
        };
    }

    public async componentDidMount() {

            try {
                const response = await axios.get<CouponModel[]>(globals.urls.allCoupons);
                store.dispatch(couponsAction(response.data)); // Updating global state
                this.setState({ coupons: response.data });
            } catch (err) {
                alert(err);
            }
        }

    public render(): JSX.Element {

        return (
            <div className="CouponList">
                <div className="top">
                    <h1>Coupon List</h1>
                </div>/
                <div className="card">
                    <Box m={4} pt={4} >
                        <Grid container spacing={6}
                            direction="row"
                            justifyContent="space-evenly"
                            alignItems="center"
                            style={{ minHeight: '80vh' }}
                        >
                            {
                                this.state.coupons.map(c => (
                                    <Grid item xs={6} sm={4} >
                                        <Card2 key={c.id} coupon={c} />
                                    </Grid>
                                ))
                            }
                        </Grid>
                    </Box>
                </div>
            </div>
        );
    }
}

export default CouponList;

此组件包含后端所有优惠券的Get 请求,并且可以正常工作。用户可以将其视为卡片列表以及带有Purchase now 的按钮和按钮。

卡片组件:

interface CardProps {
  coupon?: CouponModel;
}

export default function MediaCard(props: CardProps) {

const history = useHistory();

function handleSubmit(){ 
 if(!store.getState().authState.user) {   
  notify.error(SccMsg.NOT_LOGGED);   
   history.push('/login')  
 }
}
 
  const classes = useStyles();

  return (
    <Card className={classes.root}>
      <CardActionArea>
     
        <CardContent>
          <ThemeProvider theme={theme}>       
          <Typography variant="body2" color="textSecondary" component="p">   
                
            {'PRODUCT: ' + props.coupon.title}
            <br/>
            <br/>
          </Typography>
          <CardMedia
          className={classes.media}
          image={CouponImage}
          title="Coupons"

        />
        <br/>
          <Typography variant="body2" color="textSecondary" component="p">
          {'WHAT YOU GET: ' + props.coupon.description}
          </Typography>
          <Typography variant="h3" component="h2">
            {props.coupon.price + "$"}
          </Typography>     
          <Typography variant="body2" color="textPrimary" component="p">
            {'Only ' + props.coupon.amount + ' Left!'}
          </Typography>
          </ThemeProvider>
        </CardContent>
      </CardActionArea>
      <CardActions>
        {/* <Button size="small" color="primary">
          <span> </span>
        </Button> */}
        <Button onClick={handleSubmit} size="small" color="primary">
          PURCHASE NOW!
        </Button>
      </CardActions>
    </Card>
  );
}

我一直在尝试研究一种方法。但相关问题要么是旧的,要么对我的问题没有帮助。

希望我的问题很清楚。

谢谢。

【问题讨论】:

  • @SinanYaman 嗨,我并没有尝试发送带有GET 请求的正文。我试图通过POST 请求发送正文。
  • 抱歉,误读了:)

标签: reactjs post axios


【解决方案1】:

简单说几句:

为什么要混合基于类的组件和函数式组件?生命周期方法已在带有钩子的函数组件中实现(例如 useEffect)

我看到您在组件中使用了 store.getState(),尝试创建一些选择器(使用重新选择)并将它们挂钩(双关语)到您的组件。

const userLoggedIn: (state: RootState) => state.authState.user

购买优惠券时

发送购买优惠券操作,然后将您的应用程序置于待处理状态,假设您使用 redux-toolkit,您可以使用 createAsyncThunk 生成待处理、错误、成功和空闲状态。

这种副作用的结果可以更新您的应用程序的状态

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2017-08-14
    • 2019-07-02
    • 2018-12-11
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多