У меня есть функция щелчка по дескриптору, которая вызывается, когда мы нажимаем на строки, и идентификатор из этой строки передается в функцию handleClick, от которой извлекается идентификатор для передачи его в API. Но имеет этот формат {stdID: "02468"}, и мне нужно разделить его и просто передать числовую часть, которая равна 02468. Я использовал функцию разделения, но я получаю, что разделение ошибок - это не функция. Мне просто нужна часть значения извлекаемого объекта состояния, и я передаю ее в API, чтобы получить записи и ссылки или перейти на другую страницу. Я проверил различные существующие сообщения Stackoverflow и попытался воспроизвести то же самое, но безрезультатно. Пожалуйста, предоставьте свой вклад

import React, { PropTypes , Component } from 'react';
import {
    Panel,
    Button,
    PageHeader,
    ControlLabel,
    FormControl,
    Pagination,
    Form,
import StatWidget from '../../src/components/Widget';
var alignment = {
  marginLeft: "550px",
  marginbottom: "100px"
}

class displayDetails extends Component {

  constructor(props) {
    super(props);

      };



    render() {
        console.log('Child Component C Summary:',this.props.respData);
        console.log('Child Component E Summary:',this.props.EData);
        console.log('Child Component A Summary:',this.props.addData);
        console.log('Child Component P Summary:',this.props.PData);



        if(this.props.addData === undefined){
          this.props.addData.FIELD 1="NA";
          this.props.addData.FIELD 2="NA";
          this.props.addData.FIELD 3="NA";
          this.props.addData.FIELD 4="NA";
          this.props.addData.FIELD 5="NA";


        }

        if(this.props.PData === undefined){
          this.props.PData.FIELD 1="NA";
          this.props.PData.FIELD 2="NA";
          this.props.PData.FIELD 3="NA";


        }

        if(this.props.EData === undefined){
          this.props.EData.FIELD 1="NA";
          this.props.EData.FIELD 2="NA";
          this.props.EData.FIELD 3="NA";
          this.props.EData.FIELD 4="NA";
          this.props.EData.FIELD 5="NA";

        }

        return (
         <div> 
          <div className="col-lg-3 col-md-6">
          <StatWidget
            style="panel-primary"
            icon="fa fa-dollar fa-5x"
            count={this.props.respData.LIFE_TIME_SPEND}
            headerText="Life Time Spend"
            footerText="View Details"
            linkTo="/blank"
          />
        </div>
        <div className="col-lg-3 col-md-6">
          <StatWidget
            style="panel-green"
            icon="fa fa-phone   fa-5x"
            count={this.props.respData.BEST_HOME_PHONE}
            headerText="Best Home Phone"
            footerText="View Details"
            linkTo="/"
          />
        </div>
        <div className="col-lg-3 col-md-6">
          <StatWidget
            style="panel-yellow"
            icon="fa fa-home fa-5x"
            count={this.props.respData.RESIDENCE_COUNTRY}
            headerText="Country"
            footerText="View Details"
            linkTo="/"
          />
        </div>
        <div className="col-lg-3 col-md-6">
          <StatWidget
            style="panel-red"
            icon="fa fa-shopping-bag fa-5x"
            count={this.props.respData.BRAND_CODE}
            headerText="Brand"
            footerText="View Details"
            linkTo="/"
          />
        </div>
        <div>
          <tr>
            <td><h1>{this.props.respData.FIELD 1} {this.props.respData.FIELD 2}</h1></td>
            </tr>
        </div>

            <div className="col-lg-15">
            <Panel header={<span>Customer Profile Data </span>} >
              <div className="table-responsive">
                <table className="table table-striped table-bordered table-hover">
                    <thead>
              <tr>
                  <th> FIELD 1 </th>
                  <th> FIELD 2 </th>
                  <th> FIELD 3 </th>
                  <th> FIELD 4 </th>
                  <th> FIELD 5 </th>
                  <th> FIELD 6 </th>
                  <th> FIELD 7 </th>
                  <th> FIELD 8</th>
                  <th> FIELD 9</th>
                  <th> FIELD 10</th>
                  <th> FIELD 11</th>
                  <th> FIELD 12</th>
                  <th> FIELD 13</th>
                  <th> FIELD 14</th>
                  <th> FIELD 15</th>
                  <th> FIELD 16</th>
                  <th> FIELD 17</th>
                  </tr>
             </thead>     
             <tbody>
             <tr>
             <td>{this.props.respData.FIELD 1}</td>  
             <td>{this.props.respData.FIELD 2}</td>
             <td>{this.props.respData.FIELD 3}</td>
              <td>{this.props.respData.FIELD 4}</td>
              <td>{this.props.respData.FIELD 5}</td>
              <td>{this.props.respData.FIELD 6}</td>
              <td>{this.props.respData.FIELD 7}</td>
              <td>{this.props.respData.FIELD 8}</td>
              <td>{this.props.respData.FIELD 9}</td>
              <td>{this.props.respData.FIELD 10}</td>
              <td>{this.props.respData.FIELD 11}</td>
              <td>{this.props.respData.FIELD 12}</td>
              <td>{this.props.respData.FIELD 13}</td>
              <td>{this.props.respData.FIELD 14}</td>
              <td>{this.props.respData.FIELD 15}</td>
              <td>{this.props.respData.FIELD 16}</td>
              <td>{this.props.respData.FIELD 17}</td>
              </tr>
            </tbody>  
          </table>
           </div>
           </Panel>



          <div className="col-lg-6">
            <Panel header={<span>Phone </span>} >
              <div className="table-responsive">
                <table className="table table-striped table-bordered table-hover">
                  <thead>
                    <tr>
                      <th>FIELD 1</th>
                      <th>FIELD 2 </th>
                      <th>FIELD 3 </th>
                      <th>FIELD 4 </th>
                      <th>FIELD 5 </th>
                    </tr>
                  </thead>
                  <tbody>
             {this.props.PData.map((item, i) => {
          return (
            <tr key={i}>  
                        <td> {item.FIELD 1}</td>
                 <td> {item.FIELD 2}</td>
                 <td> {item.FIELD 3}</td>
                 <td> {item.FIELD 4}</td>
                 <td> {item.FIELD 5}</td>
             </tr>
);
        })}
            </tbody>
            </table>
              </div>
            </Panel>
          </div>

<div className="col-lg-6">
<Panel header={<span> Email </span>} >
<div className="table-responsive">
  <table className="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th>FIELD 1  </th>
        <th>FIELD 2</th>
        <th>FIELD 3</th>
        <th>FIELD 4</th>
        <th>FIELD 15</th>
      </tr>
    </thead>
    <tbody>
    {this.props.EData.map((item, i) => {
          return (
            <tr key={i}>  
                 <td> {item.FIELD 1}</td>
                 <td> {item.FIELD 2}</td>
                 <td> {item.FIELD 3}</td>
                 <td> {item.FIELD 4}</td>
                 <td> {item.FIELD 5}</td>
             </tr>
);
        })}
    </tbody>
  </table>
</div>
</Panel>
</div>

<div className="col-lg-6">
<Panel header={<span>Address </span>} >
<div className="table-responsive">
  <table className="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th> FIELD 1 </th>
        <th> FIELD 2 </th>
        <th> FIELD 3 </th>
        <th> FIELD 4 </th>
        <th> FIELD 5 </th>
        <th> FIELD 6 </th>
      </tr>
    </thead>
    <tbody>
    {this.props.addData .map((item, i) => {
          return (
            <tr key={i}>  
                 <td> {item.FIELD 1}</td>
                 <td> {item.FIELD 2}</td>
                 <td> {item.FIELD 3}</td>
                 <td> {item.FIELD 4}</td>
                 <td> {item.FIELD 5}</td>
                 <td> {item.FIELD 6}</td>
             </tr>
);
        })}
    </tbody>
  </table>
</div>
</Panel>
</div>   
<div className="col-lg-6">
<Form>
<FormGroup controlId="formControlsDisabledButton" style={alignment}>
<Button bsStyle="primary" type="submit" disabled>Save</Button>
{'  '}
<Button bsStyle="primary" type="reset" disabled>Cancel</Button>
</FormGroup>
 </Form>
 </div>
 </div>
 </div>

        )
      }
}


export default displayDetails;
0
Ice_Queen 22 Окт 2018 в 22:01

2 ответа

Лучший ответ
   import React, { PropTypes , Component } from 'react';
    import './blank.css';
    import {
      Panel,
      Button,
      PageHeader,
      ControlLabel,
      FormControl,
      Pagination,
      FormGroup} from 'react-bootstrap';
    import JwPagination from 'jw-react-pagination';
    import FormControlFeedback from 'react-bootstrap/lib/FormControlFeedback';
    import FormControlStatic from 'react-bootstrap/lib/FormControlStatic';
    import InputGroupAddon from 'react-bootstrap/lib/InputGroupAddon';
    import {Link, BrowserRouter as Router,Route} from 'react-router-dom'; 

    const customStyles = {
      ul: {
          backgroundColor: 'red'
      },
      li: {
          border: '1px solid green'
      },
      a: {
          color: 'blue'
      }
    };
    const title = 'Customer-LookUp';
    const spacing = {
      marginRight: "20px",
      marginbottom: "20px"
    }
    const buttonalignment = {
      marginLeft: "81px",
      marginbottom: "20px"
    }

    class displayBlank extends Component {
      constructor(props) {
        super(props);
        this.state = {
              newData: [],
              pageOfItems: [],
              respData:[],
              sort: {
                column: null,
                direction: 'desc',
              }
          };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.searchFunction = this.searchFunction.bind(this);
        this.setArrow = this.setArrow.bind(this);
        this.onSort = this.onSort.bind(this);
        this.onChangePage = this.onChangePage.bind(this);
        this.handleClick = this.handleClick.bind(this);
      };

      onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
      handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        const data = new FormData(form);
        const arrayValue = [];
        var i = 0;
        console.log('Data from Form:',data);
        for (let name of data.keys()) {
          const input = form.elements[name];
          const parserName = input.dataset.parse;
          const parsedValue = data.get(name);
          console.log('name',name);
          console.log('parsedValue',parsedValue);
          if (typeof(parsedValue) == 'undefined' || parsedValue == null) {
             console.log('Not Defined or Not Null')
             arrayValue[i] = "";
             data.set(name, arrayValue[i]);
      }
      else{
        data.set(name, parsedValue);
        arrayValue[i] = parsedValue;
      }
          i=i+1;
        }
    console.log('brandname:after get',arrayValue[0]);
    console.log('LastName:after get',arrayValue[2]);
    console.log('zipcode:after get',arrayValue[8]);
    var response_data = "";
    var response_jsonObj ;
    var txt = "";
    var req = {"CustomerLookupRequest" : [{
    "Field1":arrayValue[0],
    "Field2": arrayValue[1],
    "Field3":arrayValue[2],
    "Field4":arrayValue[3],
    "Field5":arrayValue[4],
    "Field6":arrayValue[5],
    "Field7":arrayValue[6],
    "Field8":arrayValue[7],
    "Field9":arrayValue[8],
    "Field10":arrayValue[9]
      }]
    };
    console.log('req string :' + req);
        fetch('API_URL', {
          headers: {
            'Accept': 'application/json, text/plain, application/xml,  */*',
            'Content-Type': 'application/json' ,
            'Access-Control-Allow-Headers': 'Content-Type',
          },
          method: 'POST',
          body: JSON.stringify(req)}
        ).then(response => {
            if (response.status !== 200) {
              console.log('Problem in fetching');
              return;
            }
            response.text().then(data => {
              console.log('Data in Console',data);
              response_data = data;
              console.log('Response Data',response_data);
              response_jsonObj = JSON.parse(response_data);
              console.log('Response JSON Object',response_jsonObj);
                this.setState({ newData:response_jsonObj});
                //console.log('customer Data in handle submit',customerData);
            });
          }).catch(error => this.setState({ error }));
          }

          handleClick(field1,field2){

            var ID = field1;
            var Name = field2;
            var newresponse_jsonObj,response_data;
            var req ={"GetCustomerRequest": [{
              "field1": field2,
              "field2": "xyz",
              "field3": field1,
              "field4": "",
              "field5": "",
              "field6": ""
              }]
              };
              fetch('API_URL', {
          headers: {
            'Accept': 'application/json, text/plain, application/xml,  */*',
            'Content-Type': 'application/json' ,
            'Access-Control-Allow-Headers': 'Content-Type',
          },
          method: 'POST',
          body: JSON.stringify(req)}
        ).then(response => {
            if (response.status !== 200) {
              console.log('Problem in fetching');
              return;
            }
            response.text().then(data => {
              response_data = data;
              //console.log('Response Data in Handle Click for Get-Customer',response_data);
              newresponse_jsonObj = JSON.parse(response_data);
              console.log('Response JSON Object for Get-Customer',newresponse_jsonObj);
                this.setState({respData:newresponse_jsonObj});
                this.setState({ pageOfItems:newresponse_jsonObj});
                this.getDetails();

            });
          }).catch(error => this.setState({ error }));

          }

          getDetails(){



              console.log('Get Customer Method:');
            <table>
            <tbody>
                 {this.state.pageOfItems.map((item, i) => {
              return (
                 <tr key={i} >
                     <td >{item.XYZ.Field1}</td>
                     <td> {item.XYZ.Field2}</td>
                     <td> {item.XYZ.Field3}</td>
                     <td> {item.XYZ.Field4}</td>
                     <td> {item.Field5}</td>
                 </tr>
              );
            })}
                </tbody>
                  </table>






          }

          searchFunction() {
            var input, filter, table, tr, td, td1, i;
            input = document.getElementById("search");
            filter = input.value.toUpperCase();
            console.log('input in searchFunction:',input);
            console.log('filter in searchFunction:',filter);
            table = document.getElementById("Search-Table");
            console.log('table in searchFunction:',table);
            tr = table.getElementsByTagName("tr");
            var innertext = table.getElementsByTagName("tr").innertext;
            console.log("innertext :",innertext);
            console.log('tr in searchFunction:',tr);
            for (i = 0; i < tr.length; i++) {
              td = tr[i].getElementsByTagName("td")[2];
              console.log('td in for before if:',td);
              if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                  tr[i].style.display = "";
                } else {
                  tr[i].style.display = "none";
                }
              }       

            }
        } 


          onSort = (column) => (e) => {
            const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
            console.log('direction',direction);
            console.log('column',column);
            const sortedData = this.state.pageOfItems.sort((a, b) => {
              if (column === 'Field1') {
                return a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
              }

              else if (column === 'Last Name') {
                return 

a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
                  }

                });


                if (direction === 'desc') {
                  sortedData.reverse();
                }

                this.setState({
                  pageOfItems: sortedData,
                  sort: {
                      direction,
                        column,
            }
                });
              };

              setArrow = (column,className) => {
                let current_className = className;

                if (this.state.sort.column === column) {
                  current_className += this.state.sort.direction === 'asc' ? ' asc' : ' desc';
                }

                console.log(current_className);

                return current_className;
              };  

          render() {

            var {custID} = this.state;
            return (
              <div id = "id1">
              <div className="row">
                <div className="col-lg-12">
              <PageHeader>Title of The Page </PageHeader>
              </div>
              </div>
            <form onSubmit={this.handleSubmit}>
            <table>
            <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field1</ControlLabel>
                <FormControl componentClass="select" id="brand"  name="brand" placeholder="select">
                <option value="Value1">Value1</option>
                <option value="Value2">Value2</option>
                <option value="Value3">Value3</option>
                </FormControl>
              </FormGroup>
              </td> 
              <td>
              <FormGroup  style={spacing}>
                <ControlLabel>Field2</ControlLabel>
                <FormControl
                  id="customerId"  name="customerId"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field3</ControlLabel>
                <FormControl
                  style={spacing}
                  id="lastname"  name="lastname"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field4</ControlLabel>
                <FormControl
                  id="firstName"  name="firstName"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field5</ControlLabel>
                <FormControl
                  id="housenumber"  name="housenumber"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field6</ControlLabel>
                <FormControl
                  id="addressline"  name="addressline"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field7</ControlLabel>
                <FormControl
                  id="zipcode"  name="zipcode"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field8</ControlLabel>
                <FormControl
                  id="email"  name="email"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td>
              <FormGroup style={spacing}>
                <ControlLabel>Field9</ControlLabel>
                <FormControl
                  id="phonenumber"  name="phonenumber"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              </tr>
              <tr>
              <td>  
              <FormGroup style={spacing}>
                <ControlLabel>Field10</ControlLabel>
                <FormControl
                  id="last4digitsphone"  name="last4digitsphone"
                  type="text"
                  placeholder="Enter Text"
                />
              </FormGroup>
              </td>
              <td></td>
              <td>
              <FormGroup style={buttonalignment}>
                <Button bsStyle="primary" type="submit">Search </Button>
                {'  '}
                <Button bsStyle="primary" type="reset">Clear </Button>
              </FormGroup>
              </td>
              </tr>
            </table>

              <div className="row ng-scope">
                <div className="col-lg-15">
                  <Panel header={<span> Search Results</span>} >
                  <div id="dataTables-example_filter" className="dataTables_filter">
                             <label htmlFor={'search'}>Search:
                               <input
                                 type="text"
                                 className="form-control input-sm"
                                 placeholder=""
                                 aria-controls="dataTables-example"
                                 id="search" onKeyUp={this.searchFunction}
                               />
                             </label>
                           </div><br></br>
                  <div id ="Search-Table" className="table-responsive">
                    <table className="table table-striped table-bordered table-hover dataTable no-footer" id="dataTables-example"  role="grid" aria-describedby="dataTables-example_info">
                    <thead>
                           <tr role="row">
                             <th>Field1</th>
                             <th>Field2</th>
                             <th className="sorting" onClick={this.onSort('Field 3','asc')} aria-sort="ascending"
                            aria-label="Rendering engine: activate to sort column descending"
                            aria-controls="dataTables-example"
                            rowSpan="1"
                            colSpan="1"
                            tabIndex="0">Field3<span className={this.setArrow('First Name')}></span></th>
                             <th className="sorting" onClick={this.onSort('Field 4','asc')}>Last Name <span className={this.setArrow('Field 4')}></span></th>
                             <th>Field3</th>
                             <th>Field4</th>
                             <th>Field5</th>
                             <th>Field6</th>
                             <th>Field7</th>
                             <th>Field8</th>
                             <th>Field9</th>
                          </tr>
                         </thead>
                     <tbody>
                     {this.state.pageOfItems.map((item, i) => {
                  return (
                     <tr key={i} onClick={()=>this.handleClick(item.Field1,item.Field2)}>
                         <td >{item.Field1}</td>
                         <td> {item.Field2}</td>
                         <td> {item.Field3}</td>
                         <td> {item.Field4}</td>
                         <td> {item.Field5}</td>
                         <td> {item.Field6}</td>
                         <td> {item.Field7}</td>
                         <td> {item.Field8}</td>
                         <td> {item.Field9}</td>
                         <td> {item.Field10}</td>
                         <td> {item.Field11}</td>
                     </tr>
        );
                })}
                    </tbody>
                      </table>
                      <div className="col-sm-6 pullRight " >
                      <JwPagination  items={this.state.newData} onChangePage={this.onChangePage} /> 
                      </div>   
                      </div>
                      </Panel>
                      </div>
                      </div>
              </form>
    <DisplayDetails respData={this.state.respData}/>
        </div>

        );
         }
          }
        export default displayBlank;

    DisplayDetails.js

    import React, { PropTypes , Component } from 'react';


    class displayDetails extends Component {


     render() {
       return <h1 >Hello World!</h1>
       {this.props.respData.map((item, i) => {
        return (
           <tr key={i} >

               <td >{item.FIELD1}</td>
               <td> {item.FIELD2}</td>
           </tr>
    );
      })}

<div className="col-lg-6">
<Panel header={<span>add</span>} >
<div className="table-responsive">
  <table className="table table-striped table-bordered table-hover">
    <thead>
      <tr>
        <th> FIELD 1 </th>
        <th> FIELD 2 </th>
        <th> FIELD 3 </th>
        <th> FIELD 4</th>
        <th> FIELD 5 </th>
        <th> FIELD 6</th>
      </tr>
    </thead>
    <tbody>
    {Object.keys(addData).map((item, i) => {
          return (
            <tr key={i}>  
                          <td> {addData[item].FIELD1}</td>
                 <td> {addData[item].FIELD2}</td>
                 <td> {addData[item].FIELD3}</td>
                 <td> {addData[item].FIELD4}</td>
                 <td> {addData[item].FIELD5}</td>
                 <td> {addData[item].FIELD6}</td>
             </tr>
);
        })}
    </tbody>
  </table>
</div>
</Panel>
</div>

      }

    }


    export default displayDetails;
0
Ice_Queen 1 Ноя 2018 в 18:18

Вы имеете в виду что-то вроде этого?

const stateObj = { stdID: "02468" }

const values = Object.values(stateObj)

// values -> ["02468"]
1
SakoBu 22 Окт 2018 в 19:23
52936112