reactjs - Unable to get this.state in React component function -
how get react component state in component function. don't have objects associated state. getting this.state undefined in board removecomment function. in board removecomment function want remove comments element on index(passed argument).
class board extends react.component { constructor(props) { super(props); this.state = { comments:[ "one", "two", "three", "four", "five" ]}; }; removecomment(index) { console.log('i called',this.state); } render() { console.log(this.state); return ( <div classname="board"> { this.state.comments.map((text,i) => { return ( <comment key ={i} index = {i} commenttext={text} removecomment={this.removecomment}/> ) }) } </div> ); } } class comment extends react.component { removecomment() { var index = this.props.index; this.props.removecomment(index); } render() { return( <div onclick={this.removecomment.bind(this)}>{this.props.commenttext}</div> ); } }
because forgot bind method removecomment
in board
component, use line:
removecomment={this.removecomment.bind(this)}
use in board
component:
<div classname="board"> { this.state.comments.map((text,i) => { return ( <comment key ={i} index = {i} commenttext={text} removecomment={this.removecomment.bind(this)}/> ) }) } </div>
Comments
Post a Comment