What I am trying to achieve is after fitlerRequest function called filterListValue should manipulate.
But what happening is on radioHandleChange it's start manipulating the filterListValue.
I think they have the same memory reference but how to make a copy of it?
export default function CustomFilter(props) {
const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState(filterListValue)
const radioHandleChange = (e, list) => {
setRadioValue(radioValue => {
let copy = [...radioValue]
copy[indexChange].value = e.target.value
copy[indexChange].id = list.id
return copy
});
}
const filterRequest = () => {
setFilterListValue(radioValue)
handleClose()
};
}
Just make copies using ...
. Although not mentioned, looks like props.filterListValue
is an array. So create a copy when starting with useState hook. Also, when setting radio value, make a copy of the item (since it is an object) so you are not mutating the state by mistake.
const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState([...props.filterListValue])
const radioHandleChange = (e, list) => {
setRadioValue(radioValue => {
let copy = [...radioValue]
let copyItem = {...copy[indexChange]};
copyItem[indexChange].value = e.target.value
copyItem[indexChange].id = list.id
return copyItem
});
}
PS:
You can destructure inside the function argument parenthesis. It is common practice:
export default function CustomFilter({filterListValue, setFilterListValue}) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.