我已经创建了一个自定义React Hook,它有一个函数,将一个动作分派给redux store。
import { useDispatch, useSelector } from "react-redux";
import { toggle } from "../state/reducers/togglePassSlice";
const useToggle = () => {
const { showpass } = useSelector((state) => state.toggle);
const dispatch = useDispatch();
const togglePassVisibility = () => {
// console.log(showpass);
dispatch(toggle(showpass));
};
return { togglePassVisibility };
};
export default useToggle;
在我的组件当我试图调用它,我得到一个错误:错误:太多的重新渲染。React限制渲染次数以防止无限循环。
import EntryCard from "../../components/EntryCard/EntryCard";
import InputGroup from "../../components/InputGroup/InputGroup";
import Input from "../../components/Input/Input";
import Button from "../../components/Button";
import { EntryPage, PageHader } from "./style";
import { Link } from "react-router-dom";
import useToggle from "../../hooks/useToggle";
const SignInPage = () => {
const { togglePassVisibility } = useToggle();
const toggle = togglePassVisibility();
return (
<EntryPage>
<PageHader to="/">AWESOME LOGO</PageHader>
<EntryCard>
<h2>login</h2>
<form>
<InputGroup>
<label htmlFor="email">Email</label>
<Input type="email" placeholder="Enter email" id="email" />
</InputGroup>
<InputGroup>
<label htmlFor="password">Password</label>
<Input type="password" placeholder="Enter password" id="password" />
</InputGroup>
<Button type="submit" full="true">
Sign in
</Button>
</form>
<span>
Dont have an account?
<Link to="/signup"> Sign up</Link>
</span>
</EntryCard>
</EntryPage>
);
};
export default SignInPage;
我如何解决这个错误,请🙏什么是一个更好的方法,这种方法与自定义钩子
看看下面这几行:
const SignInPage = () => {
const { togglePassVisibility } = useToggle();
const toggle = togglePassVisibility(); // this calls dispatch every render!
return ( /* ... render ... */ );
}
每当你的组件被渲染时,你立即调用togglePassVisibility()
,这将导致一个新的渲染。这是一个无限循环
如果您希望能够像调用toggle
一样调用togglePassVisibility
,则可以执行以下操作之一:
- 分配给
toggle
时不要调用它:
const toggle = togglePassVisibility; // <-- no parentheses
- 使用解构赋值:
const { togglePassVisibility: toggle } = useToggle();
- 在你的钩子,导出一个数组代替:
// in hooks file
const useToggle = () => {
/* ... */
return [ togglePassVisibility ];
};
// in component
const [ toggle ] = useToggle();
注意:别忘了把toggle绑定到按钮上。