In the above UI, the Input field clears on each re-render (i.e each time data changes in useEffect).
useEffect(() => {
display();
}, [data]);
The data needs to be dependent because on Delete and Add the UI must re-render to show the changes. Initially, the "Hello Red" shows in the input field but on deleting any number range (eg:3 and 4), the input field clears out.
Partial Code:
const App = () => {
const [data, setData] = useState({
Red: {
Name: "R",
List: [
["4", "6"],
["3", "4"],
["1", "2"],
["7", "10"]
]
}
});
const deleteNewRange = (key) => {
console.log(key);
let obj = { ...data };
data.Red.List.splice(key, 1);
obj = {
...data,
Red: {
...data.Red,
Name: data.Name,
List: [...data.Red.List]
}
};
setData(obj);
};
useEffect(() => {
display(); //display code can be found in below codesandbox link
}, [data]);
return (
<>
<Form>
{data.Red.List.map((range, index) => (
<div key={index}>
<Form.Item name={"startRange" index}>
<InputNumber />
</Form.Item>
<p>To</p>
<Form.Item name={"endRange" index}>
<InputNumber/>
</Form.Item>
<div>
Add
</div>
<div onClick={() => deleteNewRange(index)}>
Delete
</div>
</div>
))}
</Form>
<Button type="primary" htmlType="submit">
Save
</Button>
</>
);
};
Link to more code and other functions and object conversion: https://codesandbox.io/s/basic-antd-4-16-9-forked-dq9ngr?file=/index.js
CodePudding user response:
Your display
function is an anti-pattern, and goes against the way react reasons about state and rendering.
You want to use a pattern called "controlled components". Basically, your form values
should all be using your state, and on form change you update your state. You can read more about it here.
CodePudding user response:
it's because you have added dependency of whole state you just to add for `list' try this.
useEffect(() => {
display();
}, [data.list]);