React 生命周期钩子

Posted

技术标签:

【中文标题】React 生命周期钩子【英文标题】:React Lifecycle Hooks 【发布时间】:2018-01-25 12:00:24 【问题描述】:

我正在学习 React,现在我正在使用 Lifecycle Hooks。如何在每次重新加载页面时停止组件将数据重新呈现到表中?现在我在表中得到重复或空行数据。在我使用工作台中的 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 >Course ID</TableHeaderColumn>
                  <TableHeaderColumn dataField="title" dataSort >Title</TableHeaderColumn>
                  <TableHeaderColumn dataField="location" dataAlign="center" >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>  

    );

  

【问题讨论】:

我的猜测是使用reactjs.org/docs/react-component.html#shouldcomponentupdate 并检查是否发生了变化 谢谢,所以如果我的数据加载到 componentDidMount 并且我在其中设置了状态,那么在 shouldcomponentupdate 中我将其设置为 False,我将如何将其编码为“不要更改状态并删除为如果状态相同,即没有来自 API 的新数据,那么不要添加空行? 我所做的是检查状态,所以 this.state !== nextState 基于返回真或假。如果那不削减它检查更具体的状态。在这应该更新之后,您还可以使用componentdidupdate,如果需要,您可以设置状态 完美...将在比赛结束前尝试一下。谢谢。 【参考方案1】:

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

【讨论】:

谢谢,我不再在渲染中进行 HTTP 调用,现在它在 componentDidMount 中,我也在用相同的方法更新我的状态。

以上是关于React 生命周期钩子的主要内容,如果未能解决你的问题,请参考以下文章

Vue笔记(Vue生命周期 11个钩子)

react生命周期

Vue——生命周期和钩子函数的一些理解

Vue生命周期及钩子函数

Vue-的父组件和子组件生命周期钩子函数执行顺序

React中组件的生命周期(详细)