【问题标题】:Post table React发布表反应
【发布时间】:2020-05-06 07:18:44
【问题描述】:

我向你解释我的问题,我有一个包含多个对象的表

在这个表格下

 {id:1,title:"Campus (Pinte)", desc:"Pression - Bière Blonde - 4° Alc", detail:"Une bière blonde légère qui saura vous désaltérer comme il se doit", qty:"50 cl", img:Campus, price: 5, ctg:1, },

我目前正在像这样发布我的整个表格

postbackend = () =>{
 const config = {

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

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

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

我只想发布我的表中没有总计的所有对象

例如我只想恢复标题数量和价格

你有一个想法该怎么做。 ?谢谢内夫

【问题讨论】:

    标签: javascript reactjs post axios fetch


    【解决方案1】:

    由于this.props.items 是一个数组,您需要在数组上进行映射以创建一个新数组,其中的对象只有所需的字段。

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

    然后使用你喜欢的变量:

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

    【讨论】:

    • 它不能正常工作我收到一个空数组
    • 你在哪里收到空数组? this.props.itemsthis.state的结构是什么?
    • 我在我的 bdd 上收到 Mysql {id:1,title:"Campus (Pinte)", desc:"Pression - Bière Blonde - 4° Alc", detail:"Une bière blonde légère qui saura vous désaltérer comme il se doit", qty:"50 cl", img:Campus, price: 5, ctg:1, }, 是 JSON 上的模式
    • @Callum McClean 结构项目:[ //Bière pression > 1 - Bières {id:1,title:"Campus (Pinte)", desc:"Pression - Bière Blonde - 4° Alc",详细信息:“Une bière blonde légère qui saura vous désaltérer comme il se doit”,数量:“50 cl”,img:校园,价格:5,ctg:1,},]
    • 我已经更新了我的答案,如果这不起作用,我不确定我是否理解你的问题。
    【解决方案2】:
        postbackend = () =>{
    const { title, qty, price } = this.props.items;
    const config = {
    
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({...this.state, items: { title, qty, price } }),
     };
    
     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 }));
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-26
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2018-10-17
      • 2018-10-27
      相关资源
      最近更新 更多