React 'this' undefined when adding table row

久未见 提交于 2019-12-11 16:49:20

问题


I'm attempting to add a new row of data to a table that occurs when a user inputs text into a field and clicks a button. The button click is tied to a function (AddNewRow) which sends the data to a controller and then adds a new row to the table with the data.

The data is sent to the controller correctly and if the page is refreshed the new row is showing (because of the get request after mount) but the problem is the table doesn't update dynamically.

I keep getting a console error saying 'this is undefined' in the AddNewRow function. Ive attempted to bind 'this' to the constructor by using both '.bind(this)' and AddNewRow() => {} but it still doesn't bind?

class App extends React.Component {
constructor() {
    super();

    this.state = {
        tableData: [{            
        }],         
    };       
  }  

   componentDidMount() {
    axios.get('/Jobs/GetJobs', {
        responseType: 'json'
    }).then(response => {        
        this.setState({ tableData: response });
    });
}

AddNewRow(){

    axios.post('/Controller/CreateJob', { Name: this.refs.NewJobName.value})
        .then(function (response){               
            if(response.data.Error) {                   
                window.alert(response);
            }
        else {
                var data = this.setState.tableData;
                this.setState.tableData.push(response);
                this.setState({ tableData: data });
            }
        })}

    render() {
    const { tableData } = this.state;
    return (
        <div>
        <button onClick={() => this.AddNewRow()} >ADD</button>
        <input ref="NewJobName" type="text" placeholder="Name" />
        <ReactTable 
        data={tableData}
         /> 
        </div>
       )
    }

回答1:


Use arrow function to make this available in the then function:

axios
  .post('/Controller/CreateJob', { Name: this.refs.NewJobName.value })
  .then((response) => {
    if (response.data.Error) {
      window.alert(response);
    } else {
      this.setState(prevState => ({ 
        tableData: prevState.tableData.concat([response]) 
      }));
    }
  });


来源:https://stackoverflow.com/questions/50284049/react-this-undefined-when-adding-table-row

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