Fairly new to JS, React. Trying to use Material-table with a add row button. Add row would not add the row. One refreshing the rows are reset. I'm pretty sure I'm doing something wrong with setting/ updating the state.
export default function App() { return ( <div className="App"> <Tabl obj={{ a: "a", items: [{ x: 1 }, { x: 2 }, { x: 3 }] }} /> </div> ); }
class Tabl extends Component { constructor(props) { super(props); this.state = { obj: props.obj }; console.log(JSON.stringify(this.state.obj)); } updateState(newData) { this.setState({ obj: [...this.state.obj.items, newData] }); } render() { const currObj = this.state.obj; const column = [ { title: "a", field: "x" } ]; const tableIcons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />) }; return ( <MaterialTable data={currObj.items} columns={column} icons={tableIcons} options={{ search: false, paging: false }} editable={{ onRowAdd: (newData) => new Promise((resolve, reject) => { setTimeout(() => { this.updateState(newData); resolve(); }, 1000); }) }} /> ); } } export default Tabl;
Thanks in advance.
this.updateState method not binding to class.
You can bind in constructor like this,
constructor(props) {
super(props);
this.state = {
obj: props.obj
};
console.log(JSON.stringify(this.state.obj));
this.updateState= this.updateState.bind(this);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.