我正在尝试使用 React Context 钩子和打字稿来传递todos(初始状态)和addNewTodo(方法)。我尝试了多种解决方案,但没有成功,仍然出现错误。
PartialCannot invoke an object which is possibly 'undefined'泛型不会给上下文组件带来问题,但它在调用待办事项表单组件时给我带来错误addNewTodo。同样,未定义和空对象 {} 也会给出不同的错误。不知道如何解决它。如果我通过了any,那么 IntelliSense 将无法工作。
这是我的代码
import React, { useState, createContext, FC, useContext } from "react"
type Props = {
children: React.ReactNode,
}
interface TaskContextProps {
todos: Todo[],
addNewTodo: addNewTodo
}
const initialTodos: Array<Todo> = [
{ id: 1, text: 'buy some milk', completed: false },
{ id: 2, text: 'go to gym', completed: false }
]
export …Run Code Online (Sandbox Code Playgroud) 我正在构建一个带有反应钩子的简单计时器。我有两个按钮启动和重置。当我单击开始按钮时,handleStart 函数工作正常,计时器启动,但我不知道如何在单击重置按钮时重置计时器。这是我的代码
const App = () => {
const [timer, setTimer] = useState(0)
const handleStart = () => {
let increment = setInterval(() => {
setTimer((timer) => timer + 1)
}, 1000)
}
const handleReset = () => {
clearInterval(increment) // increment is undefined
setTimer(0)
}
return (
<div className="App">
<p>Timer: {timer}</p>
<button onClick={handleStart}>Start</button>
<button onClick={handleReset}>Reset</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
为了停止或重置计时器,我需要在 clearInterval 方法中传递一个属性。增量在 handleStart 函数中定义,因此我无法在 handleReset 函数中访问它。该怎么办?