React JS:需要拆分被检索的状态对象?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (65)

我有一个句柄点击功能,当我们点击行并且该行的id被传递到handleClick函数时调用它,该函数从那里检索ID以将其传递给API。但是这种格式是{stdID:“02468”},我需要将其拆分并传递数字部分02468。我使用了split函数但是我得到的错误拆分不是一个函数我只需要检索状态对象的值部分并将其传递给API以检索记录和链接或前往另一个页面。我已经检查了各种现有的Stackoverflow帖子并尝试复制相同但无济于事。请提供您的意见

   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": "APTOS",
              "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>
);
  })}*/


  }

}


export default displayDetails;
提问于
用户回答回答于

你的意思是这样的?

const stateObj = { stdID: "02468" }

const values = Object.values(stateObj)

// values -> ["02468"]

扫码关注云+社区

领取腾讯云代金券