Sharepoint 和 React:Web 部件 Table 网格不工作

Sharepoint and React: Web Part Table Grid Not Working

我一直在研究 React 中的数据 Tables 和网格,我想使用一两个,但我的数据没有呈现到网格中。来自 Json 的本地数据工作正常,我正在尝试使用的当前数据是 Allen 的 React Bootstrap Table http://allenfang.github.io/react-bootstrap-table/example.html#custom 但这只是我来自 Sharepoint 在线列表的列表,不是呈现,即使它正在返回并且可以通过警报或在 HTTP 响应中确认。我的代码在下面,请告诉我哪里遗漏了什么,我相信这与我如何呈现我的专栏有关,因为有几种方法会造成混乱。

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

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

  this.props.spHttpClient.get(`${this.props.siteUrl}/sites/dev-site/_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`);

        fitems = response.value

        for(var i=0;i<fitems.length;i++){
          dataArray.push(fitems[i]);
          console.log(fitems[i]); 
       }

       nameArray =  dataArray.map(function(item){
         //alert(item.Id); 

               return {
               value: item.Location, 
               title: item.Location, 
               id: item.Id,
               location: item.Location
                  };
        });

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

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

    });

return (
      <div className="container">
          <div>
               <h6>Location Search</h6>
               <div>  
              <BootstrapTable
                      data={ritems}
                      selectRow={selectRowProp}
                      striped
                      hover
                      condensed
                      pagination
                      insertRow
                      deleteRow
                      search>
                  <TableHeaderColumn dataField="id" isKey dataAlign="right" dataSort>Product ID</TableHeaderColumn>
                  <TableHeaderColumn dataField="title" dataSort>Product Name</TableHeaderColumn>
                  <TableHeaderColumn dataField="location" dataAlign="center" >Product Price</TableHeaderColumn>
                </BootstrapTable>


              </div>
          </div>
          Component 2
          <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 I am component 2
           </PanelB>
          <div>


          </div>
      </div>  

    );//Return
  }//Response
}//Class

编辑: Data not rendering from API Data rendering from local json

您好,这里为需要的人解答,希望对您有所帮助。需要注意以下几点。感谢那些试图提供帮助的人。还添加了一个 fetch() 版本。请注意,这两种解决方案都需要支架 model/Array,如下所示。

  1. 数据源错误

    data={productsGlobal} - 这是应该传入数据字段的数据源,而我传入的是 data={ritems}.

  2. 循环过滤项目

我并没有遍历筛选的项目...相反,我只是在格式化它们。我需要一个额外的 for 循环:

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

       }

3。最后发现 MUI UI 元素现在需要像这样包装在 Mui Theme Provider 中:

   `<MuiThemeProvider muiTheme={getMuiTheme()}> </BootstrapTable><AutoComplete/></MuiThemeProvider>` 

正确导入和实例化如下所示:

     `import Autocomplete from 'material-ui/AutoComplete';
// since the export is a function, this is the only actual correct way:
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
const muiTheme = getMuiTheme({});`

最终结果应该是这样的:

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

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


//Initialise data in CompDidMount is the best place
//according to best practices
componentDidMount() {
  var nameArray = [];
  var dataArray = [];
  var fitems = [];
  var ritems = [];
 // var products = [];
  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);

 });
}//Comp did mount

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

      const { isLoading } = this.state;

      if (isLoading) {
        return <p>Loading ...</p>;
      }


      const actions = [
        <FlatButton
          label="Cancel"
          primary={true}
          onClick={this.handleClose}
        />,
        <FlatButton
          label="Submit"
          primary={true}
          onClick={this.handleClose}
        />,
      ];

      var MuiAuto = [{title: ''}];
      for(var i=0;i<productsGlobal.length;i++){
        MuiAuto.push(productsGlobal[i]);
        //alert('I am ritems of item ' + nameArray[1].id);
        }


        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
        };

        const customContentStyle = {
          width: '100%',
          maxWidth: 'none',
        };


        return (


    <MuiThemeProvider muiTheme={getMuiTheme()}>
          <div className="container">
              <div>



                     <RaisedButton backgroundColor="#890458" label="View the A-Z Vic List" onClick={this.handleOpen} />
                <Dialog
                  title="A-Z Vic List"
                  actions={actions}
                  modal={true}
                  contentStyle={customContentStyle}
                  open={this.state.open}>
                  T
                  <div className={styles.azdirectory}  name="azdirectory" id="azdirectory"><br />
                      <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="25%">Title</TableHeaderColumn>
                          <TableHeaderColumn dataField="location" dataAlign="center" width="25%">Location</TableHeaderColumn>
                          <TableHeaderColumn dataField="location" dataAlign="center" width="25%">Dummy</TableHeaderColumn>
                        </BootstrapTable>
                      </div>
                 </Dialog>

              <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>
                  </div>
        </div>  

        </MuiThemeProvider>

        );
      }//end of Render
 }//end of class

获取版本:

componentDidMount() {
  var nameArray = [];
  var dataArray = [];
  var fitems = [];
  var ritems = [];
 // var products = [];
  var tableColumn: any;

 // this.setState({ isLoading: true, myAPIList: [], dataSource: [] });


  //URLs
  var CourseBooking = `https://site.sharepoint.com/sites/dev-sm/_api/web/lists/GetByTitle('CourseBookingTest')/items`;
  var AZList = `https://site.sharepoint.com/sites/dev-sm/_api/web/lists/GetByTitle('Locations')/items`;

  fetch(CourseBooking, { credentials: "include", headers: { accept: "application/json" } })
    .then(response => response.json())
    .then((response: { value: IListItem[] }) => {

          //1 Response value to fitems
          fitems = response.value;
          alert('I am fitems plus data ' + fitems + response);
          //1 for each of response item push to data array
          //2 still json object so not string
          //so not browser/ui ready
           for(var i=0;i<fitems.length;i++){
             dataArray.push(fitems[i]);
             console.log(fitems[i]); 
          }
         // alert('I am dataArray' + dataArray);

          if(fetch(CourseBooking)){
            //map the json object to another array
         //via each object key so it's stringable
         //and can be sent to browser
         //as astring if need be too if you request the formatted item
         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
                    };   
              });
          } else {

            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
                   ,Office_x0020_Type: item.Office_x0020_Type
                     };   
                 });

          }
         // alert('I am nameArray' + nameArray);
          //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);
          //finally set our data object state
          this.setState({myAPIList: response.value, isLoading: false, dataSource: response.value, open: false })
          //this.setState({dataSource: [value,value + value, value + value + value,]})
})//fetch