首页 > 解决方案 > 使用 React PNPJ 推送到 SharePoint 列表后检索 ID

问题描述

我正在构建一个 SharePoint SPFx 反应应用程序。简而言之,用户填写了我创建的表单。当用户点击提交时,使用 PNPJs:https ://pnp.github.io/pnpjs/sp/items/我将该项目添加到名为Request.

从那里我想发送一封电子邮件,其中包含他们创建的那个项目的 URL 链接。现在,我的代码将项目添加到列表中,我可以毫无问题地发送电子邮件。但是,我想获取刚刚添加到列表中的项目的 ID,以便将其添加到电子邮件中。

Request这是我将项目添加到列表中的函数的精简片段。

async submitNewRequest():Promise<any> {

    let preprocessedData;

    try {       

        // add an item to the list
        pnp.sp.web.lists.getByTitle("Requests").items.add({
            Title: this.state.Title,
            Requestor_x0020_Email: this.state.getEmail,
            Created: this.state.startDate,

        }).then((iar) => {
            console.log(iar);
            //Is this where I would get the ID 
        }); 
            
        const emailProps: EmailProperties = {
            To: [this.state.getEmail],
            Subject: "Your court requisition has been submitted.",
            Body: this.initalMessage
        };
        
    } catch(error) {

    }

    return preprocessedData;            


}

我相信我必须做的是在.then((iar) => {项目成功添加到列表时,以获取带有该项目 ID 的响应。但我不确定如何。在我const emailProps: EmailProperties是我发送电子邮件的地方,这再次有效。

通常我可以做这样的事情await sp.web.lists.getByTitle("Request").items.getById(1).get();,在控制台中我会得到这样的东西:

0:
Title: "My title here"
Description: "Description Here"
ID: 24

这是提交功能:

async _onNewRequest(event) {
    event.preventDefault();
    await this.submitNewRequest();
    this.displayPop();
}   

最后是我的电子邮件功能:

get initalMessage() {
    return `<p>This is my email template that I stripped down.</p>
    
    &nbsp;
    <p>
    <a href="https://mywebsite.sharepoint.com/sites/Requests/SitePages/Home.aspx#/MyRequests/'+ NEED_ID_HERE +'" target="_blank">
        Click Here
    </a>
</p>`; 

标签: reactjssharepointspfxpnp-js

解决方案


您可以像这样检索项目的 ID:

  sp.web.lists.getByTitle("ct0").items.add({
    Title:"test"
  }).then(iar=>{
    console.log(iar.data.ID);
  })

代码将是这样的:

  const iar=await sp.web.lists.getByTitle("ct0").items.add({
    Title:"test"
  });
  const id=iar.data.ID;
  const emailProps: EmailProperties = {
        To: [this.state.getEmail],
        Subject: "Your court requisition has been submitted.",
        Body: this.initalMessage,
        ID:id
  };

推荐阅读