Uncaught TypeError: this.state.Students.push is not a function and this.state.Students.map is not a function

Viewed 7472

What should i do?, i try many ways to solve this problem but still uncaught type error .push and .map is not function.Please help me solve this ,it will great honor for me.

var InsertArray = React.createClass({ getInitialState: function () { return { Students: [], Fname: '', Lname: '', Id: '', } },

render: function () {
    return (
        <div>
            Firstname:
            <input type="text" onChange={this.handleFN} value={this.state.value} />
            <br />
            Lastname :
            <input type="text" onChange={this.handleLN} value={this.state.value}/>
            <br />
            Student Id:
            <input type="number" onChange={this.handleId} value={this.state.value} />
            <hr />
            <button type="Submit" onClick={this.handleClick}>Submit</button>
            <button type="Submit" onClick={this.handleClickD}>Display</button>
            <br />
        </div>
        );
},

handleFN : function (value) {
    this.setState({
        Fname: value
    });
},

handleLn: function (value) {
    this.setState({
        Lname:value
    });
},

handleId: function (value) {
    this.setState({
        Id: value
    })
},

//this is where the data will be push into Student array by using push.

handleClick: function (e) {
    e.preventDefault();
    var student = {
        Fname: this.state.Fname,
        Lname: this.state.Lname,
        Id   : this.state.Id
    }
    this.setState({
        `Students: this.state.Students.push(student)`
    });
},

//And this handleClickD will be read all the data inside array and display.

handleClickD: function (e) {
    e.preventDefault();

        <div>
            <ul>`{this.state.Students.map(function (stud) {
                    return (<li key={stud.Id}>{stud.Fname}{stud.Lname}`
                </li>)
                }
                )}
            </ul>
        </div>
} });

ReactDOM.render(, document.getElementById('container'));

5 Answers

Array.push() and splice() are mutable method.

Why it's Effect react Set-state method Because of Immutability of the State.

This reason doesn't use a mutable method in Set-state. otherwise, you use the concat() and slice() Ex:-

this.setState({
    ...this.state,
    newServiceStrings: this.state.newServiceStrings.concat(newServiceName)
})





Related