http://jsbin.com/zehoceloka/1/edit
my input number is dynamic, it depends on the API how many data it has. So firstly I map it to the view. But there is also a feature where user can add new item. I trying to push a new empty array, but nothing happens. Am I doing it wrong?
class HelloWorldComponent extends React.Component {
constructor(){
super()
this.addNewRow = this.addNewRow.bind(this);
this.state = {
"rules":[
"age must be above 10",
"must wear shoe"
]
}
}
addNewRow(e){
const updated = this.state.rules.push("");
this.setState({rules:updated});
}
render() {
return (
<div>
{this.state.rules.map(obj =>
<input type="text" defaultValue={obj} />
)}
<button>Add New Rules</button>
<br /><br />
<pre>{JSON.stringify(this.state.rules,null,2)}</pre>
</div>
);
}
}
The objects in the state cannot be modify, you need to extract them, modify and then add again to the state:
addNewRow(e){
let rules=this.state.rules.slice();
rules.push('');
this.setState({rules:rules});
}
You forgot to define the click event on button, use this:
<button onClick={this.addNewRow}>Add New Rules</button>
Few issues in this line:
const updated = this.state.rules.push("");
1. Never mutate the state variable directly by this.state.a.push()
or this.state.a = ''
, always use setState
to update the value.
2. a.push()
will not return the updated array
, it will return the value pushed into array.
From Doc :
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
Check this working code:
class HelloWorldComponent extends React.Component { constructor(){ super() this.addNewRow = this.addNewRow.bind(this); this.state = { rules:[ "age must be above 10", "must wear shoe" ] } } addNewRow(e){ let updated = this.state.rules.slice(); updated.push(""); this.setState({rules:updated}); } render() { return ( <div> {this.state.rules.map(obj => <input type="text" defaultValue={obj} /> )} <button onClick={this.addNewRow}>Add New Rules</button> <br /><br /> <pre>{JSON.stringify(this.state.rules,null,2)}</pre> </div> ); } } ReactDOM.render( <HelloWorldComponent />, document.getElementById('react_example') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='react_example'/>
Please try like this:
var arr = this.state.rules.slice();
arr.push("");
this.setState({ rules: arr });
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.