我正在玩反应钩子,并遇到了使用useReducer的绊脚石。我创建了一个简单的pinPad,它存储一个引脚状态,然后将它与一个常量进行比较,然后如果2匹配则路由到登录页面。 (我知道它并不复杂!)我正在使用useReducer传递一个reducer:
function reducer(state, action) {
switch (action.type) {
case "addDigit":
return state + action.payload;
case "reset":
return "";
default:
throw new Error();
}
}
。目前我尚未实施PIN检查,而是使用组件链接到“/ LoggedIn”页面。
const [state, dispatch] = useReducer(reducer, "");
然后:
<KeyDigit
digit={v}
key={v}
className="keyDigit number"
buttonAction={e =>
state.length < 4 && dispatch({ type: "addDigit", payload: e })
}
/>
但是,当我链接到“/ LoggedIn”时,我得到一个“TypeError:buttonAction不是函数”消息,就好像在渲染组件后再次触发调度一样。
我的路由器:
<Router>
<div>
<Route exact path="/" component={App} />
<Route path="/LoggedIn" component={LoggedIn} />
</div>
</Router>
我不知道为什么在我不渲染App组件时应该调度App组件中包含的任何内容,顺便说一下,我可以手动输入“/ LoggedIn”的url并且不会出现错误消息所以它似乎与路由器有关。
KeyDigit组件:
const KeyDigit = ({ digit, className, children, buttonAction }) => {
let id = `id-${digit}`;
return (
<div
className={className}
id={id}
onClick={e => {
buttonAction(digit);
}}
>
<svg
width="100%"
height="100%"
viewBox="0 0 141 141"
xmlns="http://www.w3.org/2000/svg"
>
<circle cx="70" cy="70" r="67" className="key keyNumber" />
</svg>
<span className="keyDigitNumber">{digit}</span>
<div className="keyDigitNumber">{children}</div>
</div>
);
};
您需要在加载组件时阻止事件
<KeyDigit
digit={v}
key={v}
className="keyDigit number"
buttonAction={e => {
e.preventDefault();
state.length < 4 && dispatch({ type: "addDigit", payload: e })
}}
/>
因为你正在使用exact
/
路径,即使你在http://localhost:3000
它将加载App组件所以而不是/
使用/home
然后你将只能加载它在http://localhost:3000/home