Mutation of object in React with typescript
index.tsx
import React from "react";
import ReactDOM from "react-dom";
import MutatioIsBad from "./MutationIsBad";
let container = document.getElementById("root");
ReactDOM.render(
<div>
<MutatioIsBad words={[]}></MutatioIsBad>
</div>, container);
MutationIsBad.tsx
import React ,{ Component, Fragment} from "react";
import ListOfWords from "./ListOfWords";
import ListOfWordsPure from "./ListOfWordsPure";
import ListOfWordsSCU from "./ListOfWordsSCU";
import ListOfWordsMemo from "./ListOfWordsMemo";
interface IWord {
words:String[];
}
interface IWordState{
words:String[];
}
export default class MutationIsBad extends Component<IWord,IWordState>{
constructor(props:any){
super(props);
this.state = {words:['ram','shyam','seeta',"Geeta"]};
}
addElements=()=>{
//shallowcopy
this.state.words.push('new String');
//type one
this.setState({words:this.state.words});
//type two
//concat just return new object
// let newordsArray=this.state.words.concat("new String");
// this.setState({words:newordsArray});
//type three
//this.setState({words:[...this.state.words,"new String"]});
}
render(){
return(
<Fragment>
<ListOfWords words={this.state.words}> </ListOfWords>
<ListOfWordsSCU words={this.state.words}></ListOfWordsSCU>
<ListOfWordsPure words={this.state.words}></ListOfWordsPure>
<ListOfWordsMemo words={this.state.words}></ListOfWordsMemo>
<button onClick={this.addElements}>add more addElements</button>
</Fragment>
);
}
}
ListOfWords.tsx
import React ,{ Component} from "react";
interface IWord {
words:String[];
}
interface IWordState{
words:String[];
}
export default class ListOfWords extends Component<IWord,IWordState>{
render(){
return(
<div>
<label>class component words:{this.props.words.join(",")}</label>
</div>
);
}
}
ListOfWordsMemo.tsx
import React,{memo} from "react";
function ListOfWords(props:any){
return <div>{props.words.join(",")}</div>
}
export default memo(ListOfWords);
//memo use so we don't mutate function componennt
ListOfWordsPure.tsx
import React from "react";
interface IWord {
words:String[];
}
interface IWordState{
words:String[];
}
export default class ListOfWordsPure extends React.PureComponent<IWord,IWordState>{
render(){
return(
<div>
<label>words:{this.props.words.join(",")}</label>
</div>
);
}
}
ListOfWordsSCU.tsx
import React ,{ Component} from "react";
interface IWord {
words:String[];
}
interface IWordState{
words:String[];
}
export default class ListOfWords extends Component<IWord,IWordState>{
shouldComponentUpdate(newProps:IWord,newState:IWordState){
//=== use for address comparison
if(this.props.words ===newProps.words)
return false;
else return true;
}
render(){
return(
<div>
<label>should component words:{this.props.words.join(",")}</label>
</div>
);
}
}
Comments
Post a Comment