How to update state in onChange event in case of array object
P粉726234648
P粉726234648 2023-09-17 20:42:24
0
1
427

I have some status:

const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>();

I'm trying to use a TextField to update that state based on the input field's name and value:

budget.map((item) => { content.push(  ); });

I know this is a weird situation, but the input fields are not predetermined values so I have to render them dynamically which makes life difficult.

I tried the following onChange function but it doesn't work:

const handleChange = (event: React.ChangeEvent) => () => { const newOne = budget?.map((item) => Object.entries(item).map(([key, value]) => { if (key === event.target.name) { return [key, event.target.value]; } return [key, value]; }) ); setBudget(newOne); };

I accidentally created a lot of arrays and got the following error (not sure how to return just the keys and values):

Argument of type '(string | number | null)[][][] | undefined' is not assignable to parameter of type 'SetStateAction<{ name: string; budget: number | null; }[] | undefined>'.

P粉726234648
P粉726234648

reply all (1)
P粉993712159

I think the problem is that you are using a double arrow function in thehandleChangefunction, which means that when the event occurs, the inner function is not actually executed. You should get rid of the extra arrows.

Another problem is that you are returning an array of arrays from themapfunction, which is incompatible with your state type. You should useObject.fromEntriesto convert an array of arrays back to an array of objects. For example:

const handleChange = (event: React.ChangeEvent) => { const newOne = budget?.map((item) => Object.fromEntries( Object.entries(item).map(([key, value]) => { if (key === event.target.name) { return [key, event.target.value]; } return [key, value]; }) ) ); setBudget(newOne); };
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!