反应生命周期钩子

React Lifecycle Hooks

我正在学习 React,现在我正在使用 Lifecycle Hooks。如何停止我的组件在每次重新加载页面时将数据重新呈现到 table 中?现在我在 table 中得到重复的或空的行数据。在我使用 workbench.

中的 Sharepoint Discard 方法之前,数据也不会出现

我的组件如下:

import * as React from 'react';
import styles from './AZ.module.scss';
import { IAZProps } from './IAZProps';
import { escape } from '@microsoft/sp-lodash-subset';

import {
  SPHttpClient,
  SPHttpClientResponse,
  ISPHttpClientOptions    
} from '@microsoft/sp-http';
import { IListItem } from './IListItem';
import * as ReactDom from 'react-dom';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField,
  PropertyPaneCheckbox,
  PropertyPaneDropdown,
  PropertyPaneToggle,
  IWebPartContext
} from '@microsoft/sp-webpart-base';

//Datatables
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import PanelA  from './CompNote';
import PanelB from './CompNoteBoard'

export interface ISPLists {
  value: ISPList[];
}

export interface ISPList {
  Id: string;
  Title: string;
  Office_x0020_Type: string;
  Path: string;
}


//local data
var products = [{
      id: 1,
      name: "Product1",
      price: 120
  }, {
      id: 2,
      name: "Product2",
      price: 80
  }];

  var productsGlobal = [{
    id: '',
    title: '',
    location: ''}];

var myAPIList = [];
var faker = require('faker');
var externalData = faker;

export interface INpmsharepoint2State {
 // isOpen: Boolean;
 myAPIList;
}

export default class AZ extends React.Component<IAZProps, INpmsharepoint2State> {

      private spHttpClient: SPHttpClient;
      private contacts: ISPLists[];
      private webAbsoluteUrl: string;

      constructor(props) {
        super(props);
        this.state = { myAPIList:  []}; 


}//constructor

componentDidMount() {

}

componentWillMount(){
  }

public render(): React.ReactElement<IAZProps> {

  var nameArray = [];
  var dataArray = [];
  var fitems = [];
  var tableColumn: any;

  this.props.spHttpClient.get(`${this.props.siteUrl}/sites/dev-sm/_api/web/lists/GetByTitle('CourseBookingTest')/items`,
  SPHttpClient.configurations.v1,
    {
      headers: {
        'Accept': 'application/json;odata=nometadata',
        'odata-version': ''
      }
    })
    .then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => {
      //alert(`Successfully loaded ` + response.json() + ` items`);
      return response.json();
    })
    .then((response: { value: IListItem[] }) => {

        alert(`Successfully loaded ` + response.value.length + ` items`);

        //1 Response value to fitmes
        fitems = response.value

        //1 for each of response item push to data array
        //2 still json object so not string
         for(var i=0;i<fitems.length;i++){
           dataArray.push(fitems[i]);
           console.log(fitems[i]); 
        }

       //map the json object to another array and
       //via each object key so it's stringable
       //and can be sent to browser
       nameArray =  dataArray.map(function(item){
         //alert(item.Id); 
            //alert(data2[0].title);
               return {
               value: item.Title, 
               title: item.Title, 
               id: item.Id,
               location: item.Location
                  };
        });

        //push to a more usable array 
        for(var i=0;i<nameArray.length;i++){
          productsGlobal.push(nameArray[i]);
          //alert('I am ritems of item ' + nameArray[1].id);

       }
        alert('I am productsglobal of item ' + productsGlobal[1].title);

    }, (error: any): void => {

        alert('Loading all items failed with error' + error);

    });

    var selectRowProp = {
      mode: "checkbox",
      clickToSelect: true,
      bgColor: "rgb(238, 193, 213)" 
    };


    // The gray background
    const backdropStyle = {
      position: 'fixed',
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      backgroundColor: 'rgba(0,0,0,0.3)',
      padding: 50
    };

    // The modal "window"
    const modalStyle = {
      backgroundColor: '#fff',
      borderRadius: 5,
      maxWidth: 500,
      minHeight: 300,
      margin: '0 auto',
      padding: 30
    };

    return (
      <div className="container">
          <div>
               <h6>Location Search</h6>
               <input type='text' width='20' id='meta-area' placeholder="Start typing..."/>
                 <input id='meta_search_ids' value='' />
                 <br /><br />

                 <div className={styles.vicinfo} ><br />
                 <strong>You selected the following location:</strong><br />
                 <form>
                    ID:<span> <input id="id"  value='' /></span>
                     <br />
                      Title: <span><input id="label"  value=''  /></span>
                     <br />
                      Address:<span> <input id="address"  value=''/> </span>
                      </form>
                 </div>


          <br /><br /><br />
        <p>{escape(this.props.description)}</p>
              <div href='https://github.com/SharePoint/sp-dev-docs/wiki' >
            Learn more
              </div>
              <input  id="btnShowSecondComp" type="submit" value="View Locations Directory"/>

              <div>  


              <BootstrapTable
                      data={productsGlobal}
                      selectRow={selectRowProp}
                      striped
                      hover
                      condensed
                      pagination
                      insertRow
                      deleteRow
                      search>
                  <TableHeaderColumn dataField="id" isKey={true} dataAlign="right" dataSort width="5%">Course ID</TableHeaderColumn>
                  <TableHeaderColumn dataField="title" dataSort width="5%">Title</TableHeaderColumn>
                  <TableHeaderColumn dataField="location" dataAlign="center" width="5%">Location</TableHeaderColumn>
                </BootstrapTable>


              </div>
          </div>
          Component 3
          <PanelB count={10} 
          key={null} onChange=""
          index={null} id={null} onRemove details="" description={this.props.description} text="" title="" category={this.props.category} image={this.props.image}> 
           Hello World
           </PanelB>
          <div>


              </div>
    </div>  

    );

  }
}

不要在 render 方法中进行 http 调用! 例如,您可以在 c̶o̶m̶p̶o̶n̶e̶n̶t̶W̶i̶l̶l̶M̶o̶u̶n̶t̶ componentDidMount componentDidMount 中执行此操作,并在状态中设置 return 值。 当您更新状态时,React 将调用 render 方法并重绘您的组件。