'How can I change the child component state from parent when the parent passing the same value to child continuously?
Here is my code:
Parent.js
import { useReducer } from 'react';
import Child from "./Child";
let reducer = (state, action) => {
let result = { ...state };
switch (action.type) {
case "backward":
case "forward":
result.action=action.type;
break;
default:
break;
}
return result;
}
export default function Parent() {
const [objList, updateObjList] = useReducer(reducer, { action: "init", initValue: 1 });
let forward = () => {
updateObjList({ type: "forward" });
}
let backward = () => {
updateObjList({ type: "backward" })
}
return (
<>
<Child
action={objList.action}
initValue={objList.initValue}
/>
<div className='mt-2'>
<button className='me-2' onClick={forward}>+</button>
<button onClick={backward}>-</button>
</div>
</>
)
}
Child.js
import { useEffect,useReducer } from 'react';
let reducer = (state, action) => {
let result = { ...state };
switch (action.type) {
case "backward":
result.oldValue--;
result.newValue--;
break;
case "forward":
result.oldValue++;
result.newValue++;
break;
case "init":
result.oldValue=action.value;
result.newValue=action.value+1;
break;
default:
break;
}
return result;
}
export default function Child({action,initValue}){
const [objList, updateObjList] = useReducer(reducer, {oldValue:null,newValue:null});
useEffect(()=>{
switch (action){
case "init":
updateObjList({type:"init",value:initValue});
break;
case "backward":
case "forward":
updateObjList({ type: action });
break;
}
},[action])
return (
<>
{objList.oldValue},
{objList.newValue}
</>
)
}
It works fine. Except when the user clicks the plus or minus button more than one time, the child component only responds once.
I want the child component maintain the value, not the parent component.
How can I update the child state continuously?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|