score:0
i think you are getting confused here with const keyword. as the arrays in javascript are references, you are mutating the state.
when you declare const initialstateoflist with array, you will be freely able to add variables to this variable. "const" here means once declared you cannot re-assign that variable. but inside array, the elements can be changed.
e.g.
const arr1 = [1,2,3];
arr1.push(4); // possible. no error
arr1 = [1,2,3,4]; // not possible.
so, every time you have to create new array and don't mutate the original array refernece.
score:0
the reason is you are mutating list
in state which is not allowed in react,
import react , {component} from 'react';
import {render} from 'react-dom';
const initialstateoflist = [1,2,3,4,5];
class form extends component{
state = {
tempo : '',
list : initialstateoflist
};
cleararray=()=>{
this.setstate({list:[]});
}
resetarray=()=>{
this.setstate({list:initialstateoflist});
}
tempadd=(event)=>{
this.setstate({tempo:event.target.value});
}
//read comment
additem=(event)=>{
event.preventdefault();
// here you are mutating list in state, never do this in react instead you can use spread operator to create new array
//this.state.list.push(this.state.tempo);
const newlist = [...this.state.list, this.state.tempo]
this.setstate({tempo:'', list: newlist});
}
render(){
const listitem = this.state.list.map((number) => <li>{number}</li>);
return(
<div>
<form ref="form" id="getinput" onsubmit={this.additem}>
{this.state.list.map((listitem)=><li>{listitem}</li>)}
<input type="text" ref="formtext" id="adder" onblur={this.tempadd} />
<input type="submit" ref="formsubmit" id="passer" />
<button id="clear" onclick={this.cleararray}>clear</button>
<button id="reset" onclick={this.resetarray}>reset</button>
</form>
</div>
);
};
}
score:0
you mutated directly initialstateoflist
with push
at
this.state.list.push(this.state.tempo)
that cause the issue. you need to clone the array before mutating.
have a lot of ways to clone an object (array is a type of object) to avoid mutate directly.
const { list, tempo } = this.state // should use object destructuring for clean code
const newlist = object.assign({}, list) // object.assign
const newlist1 = [...list] // spread syntax
const newlist2 = _.clone(list) // `lodash` library
newlist.push(tempo)
this.setstate({list: newlist, tempo: ''})
score:1
you can try to reset to the original state using a custom reset function:
import react, { component } from 'react';
const getdefaultstate = () => ({
myarray: [1,2,3],
});
class mycomponent extends component {
constructor(props) {
super(props);
this.state = { ...getdefaultstate() };
}
componentdidmount() {
this.setstate({ myarray: [4,5,6] })
}
resetstate = () => {
this.setstate({ ...getdefaultstate() });
};
render() {
return (
<div onclick={this.resetstate}>
{json.stringify(this.state.myarray)}
</div>
);
}
}
Source: stackoverflow.com
Related Query
- reset array in react does not go to original state
- React does not re-render updated array state
- React does not refresh after an update on the state (an array of objects)
- why filtering state array with react hooks doesn't work but filtering original array does
- useState react hook does not set the array state
- React State not updating and getting reset to original state
- React - setting state with data does not work/ sets its to an empty array - why?
- React hooks useState initialization does not reset the state
- React jsx array component does not re-render when state changes
- React setState does not update a state array value
- React useState hook does not shows correct state of array
- Rendering React app does not apply when adding items to an array inside a state
- React does not re-render when updating state of Array of Objects
- React event target value from jsx element does not get bind to state and json array (Type error cannot read the properties of undefined )
- React array.splice on state array does not update dom properly?
- setState does not update array state in React Js
- React Hook error in array handing in useEffect() and setState does not set the state
- Why does calling react setState method not mutate the state immediately?
- React - useState - why setTimeout function does not have latest state value?
- State using React Typescript: Property does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes
- React leaflet center attribute does not change when the center state changes
- React not re-rendering after array state update
- React Dev Tools does not show Component Names or State Variable Names
- React hooks - state in useState() is not reset when route is changed
- react component state change after ajax call but does not rerender component
- onMouseDown event in react does not trigger state changes but onClick does
- React js changing state does not update component
- Changing object property in an array with React Hooks does not evoke a re-render
- React Formik checkbox group does not turn into an array of invidual checked or unchecked elements
- React not updating state with setState with Array of object
More Query from same tag
- Cannot create react app template. npm hangs
- Redux - why loading everything in state at root
- Is it possible to restrict to multiple roles in react-admin?
- Why is React's filesize so big given its small API?
- How to trigger child component function
- Want hide all row select option but not multiple row select options from MUIDatatables.Is it possible?
- Next.js: Navigate to other page without re-render
- Uncaught TypeError: Object(...) is not a function at eval (global-styles.js)
- Can't seem to get containers aligned properly even though I am using flexbox
- Where should I load data from server in Redux + ReactJS?
- react-router-dom with TypeScript
- How to extract props from response.data with get method
- fetch json file on react component render,using async await
- React.memo not re render if props change
- React: Unable to change value by a function in setState
- React-draggable npm package prevents clicking inside input field
- Material UI - How to ListItem link to open a dialog
- Carousel Transitions not Responding
- React styled-component / e2e testing: What is the best way to use css selector?
- Typescript - What type of function is it?
- React Input don't change when I set a initial value
- React conditional router for Cordova
- React component only rendering one item in my object
- React Router 4 Failed context type
- Why do i get this Webpack loader Error?
- ant-design breadcrumbs with ID
- React - Get the component name in functional components
- Store is refreshed but dispatch is not rendering new view
- How to Render Components to react-sidebar main content view
- how to pass parameter value in useEffect by function