我正在用NodeJS开发一个React应用程序。我目前正在努力能够在几分钟不活动后注销用户,我正在遵循这个教程:https://www.youtube.com/watch?v=_wgCPufTAYI。我没讲太远,因为导入IdleTimer时会出现这个错误。此外,我没有'npm install react-idle-timer',所以这应该不是原因。我不明白为什么会这样,所以任何帮助都是非常感激的!谢谢你
这是错误发生的地方
import React, { useRef } from 'react';
import IdleTimer from 'react-idle-timer';
function SessionTimeout() {
const idleTimerRef = useRef(null);
const onIdle = () => {
console.log('User is idle');
}
return (
<div>
<IdleTimer ref={idleTimerRef} timeout={5 * 1000} onIdle={onIdle}></IdleTimer>
</div>
)
}
export default SessionTimeout
这是错误
ERROR in ./src/pages/SessionTimeout.js 20:35-44
export 'default' (imported as 'IdleTimer') was not found in 'react-idle-timer' (possible exports: IdleTimerConsumer, IdleTimerContext, IdleTimerProvider, createMocks, useIdleTimer, useIdleTimerContext, withIdleTimer, workerTimers)
@ ./src/App.js 21:0-52
@ ./src/index.js 7:0-24 11:33-36
webpack 5.70.0 compiled with 1 error and 1 warning in 266 ms
change
import IIdleTimer from 'react-idle-timer'
到
import { IIdleTimer } from 'react-idle-timer'
库不导出默认值
似乎他们在v5中改变了他们的api所以现在你必须像这样导入钩子
import {useIdleTimer} from 'react-idle-timer'
....
// Hook
const idleTimer = useIdleTimer({
crossTab: true
})
// Higher Order Component Wrapped
<IdleTimer crossTab />
`import { useIdleTimer } from 'react-idle-timer';`
export default function IdleComponent() {
const idleTimeRef = useRef(null);
const onIdle = () => {
console.log('Log Out');)};
const idleTimer = useIdleTimer({
crossTab: true,
ref: idleTimeRef,
timeout: 60 * 3 * 1000,
onIdle: onIdle})
return (<div idleTimer={idleTimer}></div>);
}
格式化Mithlesh Kumar的代码片段:
import { useRef } from "react";
import { useIdleTimer } from "react-idle-timer";
export default function IdleComponent() {
const idleTimeRef = useRef(null);
const onIdle = () => {
console.log("Log Out");
};
const idleTimer = useIdleTimer({
crossTab: true,
ref: idleTimeRef,
timeout: 60 * 3 * 1000,
onIdle: onIdle,
});
return <div idleTimer={idleTimer}></div>;
}
详细信息请参考文档