我正在玩React钩子,并遇到了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”的网址,而错误消息却没有发生,因此似乎与路由器有关。
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>
);
};
答案 0 :(得分:1)
您需要在加载组件时阻止事件
void main(void)
{
TRISCbits.TRISC5 = 0; //Set TRIS of C5 to output
LATCbits.LATC5 = 0; //Set output value of C5 to 0
RC5PPS = 0x6; //Connect C5 to CCP2 output
CCP2CON = 0x1C; //Set CCP4 to PWM mode, left aligned
CCPR2L = 0xC0; //Set CCP2 low duty cycle register to 100%
CCPR2H = 0xFF; //Set CCP2 high duty cycle register to 100%
CCPTMRS0bits.C2TSEL = 0x0; //set CCP2 timer source to timer 2
PIE7bits.CCP2IE = 0; //Turn off CCP2 interrupt
T2RST = 0x00;
T2PR = 0xFF; //Set timer 2 PR register to FF
T2TMR = 0x00; //Set timer 2 count register to 0
PIE5bits.TMR2IE = 0; //Set timer 2 overflow interrupt off
T2HLT = 0x00;
T2CLKCON = 0x01; //Set timer 2 clock source to Fosc/4
T2CON = 0xD0; //Set timer 2 on, 1:32 prescaler
CCP2CONbits.EN = 1; //Turn on CCP2
while (1)
{
}
}
使用<KeyDigit
digit={v}
key={v}
className="keyDigit number"
buttonAction={e => {
e.preventDefault();
state.length < 4 && dispatch({ type: "addDigit", payload: e })
}}
/>
exact
路径时,即使您在/
它将加载App组件,因此请使用http://localhost:3000
而不是/
那么您将只能将其加载到/home