简体   繁体   中英

React using state array without mutation

Can the below code be refactored so as to not mutate the state array. Basically, I want that as I navigate the app back and forth via props.history.push, it should not recreate the array, as I my aim is to preserve the selected option.

const [options1, setOptions1] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
]);
const [options2, setOptions2] = useState([
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]);

let finalOpts = options1; // Is there a better way to do this ?
if (someConditionIsTrue) {
    finalOpts = options2;
}

const [selectedOpt, setSelectedOpt] = useState(finalOpts[0]);

<MyList
    id="myDD"
    selectedOpt={selectedOpt}
    options={finalOpts}
/>

Use useMemo to precalculate the values if your UI logic depends on some conditional. This alone will not preserve the selectedState if the component is unmounted. In order to preserve the selected state even after the component has been unmounted, you will have to store the selection in some kind of global state.


const options = useMemo(() => {
  if(someConditionIsTrue) {
    return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2}
    ];
  }
  return [
    {value: 'ABC', text: 'ABC', id: 1},
    {value: 'DEF', text: 'DEF', id: 2},
    {value: 'XYZ', text: 'XYZ', id: 3}
]
}, [someConditionIsTrue]);

const [selectedItem, setSelectedItem] = useState();



return (<MyList
    id="myDD"
    selectedOpt={selectedItem || options[0]}
        onSelectionChanged={setSelectedItem}
    options={options}
/>)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM