NodeJS 从“react-idle-timer”导入IdleTimer时出错

t5fffqht  于 2022-12-22  发布在  Node.js
关注(0)|答案(3)|浏览(102)

我正在用NodeJS开发一个React应用程序。我目前正在研究如何在用户不活动几分钟后注销用户,我正在遵循以下教程:https://www.youtube.com/watch?v=_wgCPufTAYI。我没有得到太多,因为我得到这个错误时,我导入IdleTimer。此外,我没有'npm安装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
r55awzrz

r55awzrz1#

变化

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 />
j0pj023g

j0pj023g2#

`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>);
}
kmpatx3s

kmpatx3s3#

格式化Mithlesh Kumar's代码片段:

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>;
}

有关详细信息,请参阅documentation

相关问题