문제

I'm trying to add an item in SharePoint Online list using SPFx solution where I'm using React JS to perform the action.

Below is the copied code, when debugging it says that:

"VM242:1 Uncaught TypeError: Cannot read property 'spHttpClient' of undefined"

Please have a look at the below code and let me know if I'm missing out on any thing.

I'm just trying to add an item in list called test.

function _alertClicked(): void {
  alert('Clicked');
  //Custom
  const body: string = JSON.stringify({
    'Title': `Item ${new Date()}`
  });
  this.context.SPHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('test')/items`,
    SPHttpClient.configurations.v1,
    {
      headers: {
        'Accept': 'application/json;odata=nometadata',
        'Content-type': 'application/json;odata=nometadata',
        'odata-version': ''
      },
      body: body
    })
    .then((Response: SPHttpClientResponse): Promise<IListItem> => {
      return Response.json();
    })
    .then((item: IListItem): void => {
      this.updateStatus(`Item 'Test' Successfully Created`);
    }, (error: any): void => {
      this.updateStatus('Error' + error);
    });

}

Note: I'm using fabric controls on the page.

올바른 솔루션이 없습니다

다른 팁

Declare a props of SPHttpClient type in your Webpart's Props.ts file as below :

import { SPHttpClient } from "@microsoft/sp-http";

export interface WebpartProps { 
   spHttpClient: SPHttpClient;
}

Go to your Webpart's .ts file :

import { SPHttpClient, SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http';

public render(): void {
   const element: React.ReactElement<IHomepageProps> = React.createElement(
     Webpart, //this name will be your webpart name
     {
        spHttpClient: this.context.spHttpClient,
     }
   );
 }

Now you should be able to pass it in your .tsx file as below :

this.props.spHttpClient
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 sharepoint.stackexchange
scroll top