ReactAXIOS POST方法

jmp7cifd  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(155)

我在调用Axios时出错,在通过手柄点击按钮React时,我已经创建了一个onlick函数。我在最后一个结束括号中遇到错误。错误显示第24:2行:解析错误:意外令牌,预期为“,”(24:2)enter image description here作为初学者,我无法理解有什么问题请查看代码并告诉我handleProducts函数有什么问题

const NewProduct = (props) => {
  const [carCompany, setcarCompany] = React.useState([]);
  const [carName, setcarName] = React.useState([]);
  const [carModel, setcarModel] = React.useState([]);
  const [carPrice, setcarPrice] = React.useState([]);
  const [Features, setFeatures] = React.useState([]);
  const handleProducts = () => {
    axios
      .post("http://localhost:4000/products/create", {
        carCompany,
        carName,
        carModel,
        carPrice,
        Features,
      }
        .then(res=>{console.log(res.data);
        })
        .catch(error => {
          console.error(error);
        });
  };
  return (
    <Grid container spacing={3}>
      <Grid item xs={12}>
        <h1>Enter Car details for Sale</h1>
      </Grid>

      <Grid item xs={3}></Grid>

      <Grid item xs={6}>
        <TextField
          id="filled-basic"
          fullWidth
          label="Car Company"
          variant="filled"
          value={carCompany}
          onChange={(e) => setcarCompany(e.target.value)}
        />
        <TextField
          id="filled-basic"
          fullWidth
          label="Car Name"
          variant="filled"
          value={carName}
          onChange={(e) => setcarName(e.target.value)}
        />
        <TextField
          id="filled-basic"
          fullWidth
          label="Model"
          variant="filled"
          value={carModel}
          onChange={(e) => setcarModel(e.target.value)}
        />
        <TextField
          id="filled-basic"
          fullWidth
          label="Price"
          variant="filled"
          value={carPrice}
          onChange={(e) => setcarPrice(e.target.value)}
        />

        <TextField
          id="filled-basic"
          fullWidth
          label="Features"
          variant="filled"
          value={Features}
          onChange={(e) => setFeatures(e.target.value)}
        />
      </Grid>
      <Grid item xs={3}></Grid>

      <Grid item xs={3}></Grid>
      <Grid item xs={9}>
        <Button color="primary" variant="contained" onClick={handleProducts}>
          Add Details
        </Button>
      </Grid>
      <Grid>
        {carCompany}
        {carName}
        {carModel}
        {carPrice}
        {Features}
      </Grid>
    </Grid>
  );
};
export default NewProduct;
hjzp0vay

hjzp0vay1#

您错过了应该结束post方法调用的方括号。我建议您使用一致的缩进,这样您将来可以更清楚地看到这一点。如何缩进代码由您决定-您可以将function callthencatch放在同一列中,也可以用对您更清楚的任何其他方式来组织它。
以下是handleProducts的固定代码:

const handleProducts = () => {
  axios.post("http://localhost:4000/products/create", {
    carCompany,
    carName,
    carModel,
    carPrice,
    Features, 
  }).then(res => { 
       console.log(res.data); 
  }).catch(error => { 
       console.error(error); 
  });
};

相关问题