Sending row/cell data on click to the function - ReactJS

偶尔善良 提交于 2019-12-13 02:26:51

问题


I am retrieving table data from componentWillMount and showing it as UI. I want to trigger a fuction when the row/cell is clicked and return that value back to another PHP so that i can query the backend using that retrieved cell value.

  • index = 0,1,2,3 ( I have 4 columns )
  • row = data for each index.

I am not sure why this.state.testTime is not sending the correct value to handleClick function. Does anyone have any inputs on this? Thanks.

 _handleClick: function (event) {
        this.setState({testTime: event.target.value});
        console.log(event.target.value);    
        var data = {
            testTime: this.state.testTime
        }

        console.log("clicked");
        $.ajax({
            type: "GET",
            crossDomain: true,
            url: "http://localhost:8080/TEST/capture.php",
            data: data,
            success: function(data){
                alert(data);
            },
            error:function(data)
            {
                alert("Data sending failed");
            }
        });
    },

return (
<tbody>
 {tableData.map((row, index) => {
       return (
              <tr key={"row_" + index} >
                {row.map((cell, index) => {
                    return (
                        <td key={"cell_" + index} onClick={this._handleClick} value={this.state.testTime} >{cell}</td>
                         );
                 })}
              </tr>
             );
  })}
</tbody>
)

回答1:


setState is an async function and it accepts a callback as the second argument that will be executed once setState is completed and the component is re-rendered. So you either need to use event.target.value directly for the data variable or put your code into the callback:

this.setState({testTime: event.target.value} ,() => {
   var data = {testTime: this.state.testTime}
   ...
   $.ajax...
});


来源:https://stackoverflow.com/questions/39156249/sending-row-cell-data-on-click-to-the-function-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!