[英]React Hooks: How could I fill a modal component after a button click?
I coded a modal component: Modal
that has this props:我编写了一个模态组件: Modal
有这个道具:
interface IProps {
isShowing: boolean,
hide(): void,
category: ICategory
}
This modal is a form that contains only one input:此模态是一种仅包含一个输入的表单:
const [name, setName] = useState(props.category.name)
// Other bunch of code.
const editCategory = (e: React.FormEvent) => {
e.preventDefault()
const editedCategory: ICategory = {
id: props.category.id,
name
}
// Dispatch Action...
props.hide()
}
<label>Category Name</label>
<input value={name} onChange={e => { setName(e.target.value) }} />
<button onClick={editCategory}>Edit Category</button>
<button onClick={props.hide}>Cancel</button>
The Parent component has父组件有
const {isShowing, toggle} = useEditModal()
const [category, setCategory] = useState<ICategory>({id: 0, name: ""})
const updateCategory = (item: ICategory) => {
setCategory(item)
toggle()
}
// foreach to create the table and so on...
<th> <button onClick={ () => { updateCategory(item) }}>Update category</button> </th>
// More code...
<ModalEditCategory isShowing={isShowing} hide={toggle} category={category} />
So everything runs as expected except that the form is not displaying the current state of the selected category.所以一切都按预期运行,除了表单没有显示所选类别的当前 state。 So:所以:
const updateCategory = (item: ICategory) => {
setCategory(item)
toggle()
}
The set category happens after i toggle the modal.设置类别发生在我切换模态之后。 I know that this is the correct and asynchronous way of setState hooks in React but, Is there a way to fill the form after i update the state?我知道这是 React 中 setState 挂钩的正确和异步方式,但是,在我更新 state 之后,有没有办法填写表格?
I know that there is a hook called useeffect, but the i entered on a infinite loop trying to show the modal.我知道有一个名为 useeffect 的钩子,但我进入了一个无限循环,试图显示模态。
Thanks in advance.提前致谢。
useEffect is the best way to do this. useEffect 是执行此操作的最佳方法。 However the "toggle" function would be a different object on every render, causing the useEffect to be triggered.但是,“切换”function 在每次渲染时都是不同的 object,从而导致触发 useEffect。
To prevent this, wrap the function "toggle" with a "useCallback" hook and then use it.为防止这种情况,请使用“useCallback”挂钩包装 function“切换”,然后使用它。
const toggleMemoized= useCallback(() => {
toggle();
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.