Reputation: 29
var array= []
class Body extends Component {
state= {
input: '',
oprStatus: false,
check: false,
count: 0,
oprArray: null
} }
now as i know that i cant update the 'oprArray' array inside the state by using push so what i was thinking that what if i declare a variable outside the class and update that array and then update the 'oprArray' inside state
array.push(2);
this.setState({
oprArray: array
)}
Upvotes: 0
Views: 301
Reputation: 1074058
That doesn't solve the problem, because you'd still be mutating state rather than setting new state. Once you've set oprArray: array
in your state the first time, the state and the global array
variable are both pointing to the same array. The next time, that push
is modifying state directly — which is a no-no with React state.
To add a new item into your oprArray
, you do it like this:
this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]}));
That:
Uses the callback form of setState
, which is necessary when you're modifying state (a new oprArray
with the new entry, 2
) based on existing state (the previous contents of oprArray
).
Creates a new array with the additional item, via spread notation.
Live Example:
const {Component} = React;
class Body extends Component {
state = {
input: '',
oprStatus: false,
check: false,
count: 0,
oprArray: null
};
componentDidMount() {
// Since your state starts with `null`, I assume you receive initial data
// via ajax or similar; emulated here with a timeout
setTimeout(() => {
this.setState({oprArray: [0, 1]}); // Initial data isn't based on existing state
// Now set up getting more data later
setTimeout(() => {
// Additional data
this.setState(({oprArray}) => ({oprArray: [...oprArray, 2]}));
}, 800);
}, 800);
}
render() {
const {oprArray} = this.state;
return (
<div>oprArray: {oprArray ? oprArray.join(", ") : "(none)"}</div>
);
}
}
ReactDOM.render(<Body />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
Upvotes: 2