Sharepoint和React:Web部件表格不起作用

时间:2018-01-17 09:44:32

标签: twitter-bootstrap reactjs sharepoint-online

我一直在研究React中的数据表和网格,我想使用一两个,但我的数据没有渲染到网格中。来自Json的本地数据工作正常,我正在尝试使用的当前数据是Allen的React Bootstrap表http://allenfang.github.io/react-bootstrap-table/example.html#custom,但它只是我的Sharepoint Online List列表,即使它被返回也无法呈现,可通过警报确认或在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

1 个答案:

答案 0 :(得分:0)

你好,这里是需要它的人的答案,因为它可能有所帮助。需要注意的是以下几点。感谢那些试图帮助的人。还添加了fetch()版本。请注意,这两种解决方案都需要一个支架型号/阵列,如下所示。

  1. 数据来源错误

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

  2. 循环过滤过的商品

  3. 我当时没有遍历已过滤的项目...而是我只是格式化它们。我需要额外的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主题提供程序中,如下所示:

       `<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