打字稿使用状态<string>引用错误:未定义字符串



import React, {
FunctionComponent,
useState,
useEffect
} from 'react'
const SearchBar: FunctionComponent = () => {
const [searchValue, setSearchValue] = useState < string > ('')
const [isSuggestionOpen, setIsSuggestionOpen] = useState < boolean > (false)
async function showSuggestedWords(event) {
setSearchValue(event.target.value)
try {
const res = await fetch(`https://www.someurl.com/q=${searchValue}`)
const suggestedWordsArray = await res.json()
// setSuggestedWords(suggestedWordsArray[1].slice(0, 10))
setIsSuggestionOpen(true)
return
} catch {
console.log('error fetching suggested results')
setIsSuggestionOpen(false)
}
}

return ( <
div >
<
form action = "/Controller"
method = "get" >
<
input name = "q"
type = "text"
value = {
searchValue
}
onChange = {
showSuggestedWords
}
autoComplete = "off"
autoCapitalize = "off"
autoCorrect = "off"
spellCheck = "false"
placeholder = "Search here" /
>
<
button type = "submit" >
Submit <
/button> <
/form> <
/div>
)
}

ReactDOM.render( <
div > < h1 > Hello, world! < /h1> <SearchBar / > < /div>,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.0.3/typescript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

我刚开始打字,所以这可能是一个显而易见的解决方案。

我有一个用React、Nextjs和Typescript制作的项目。

我使用typescript来定义我的状态类型,如下所示:const [searchValue, setSearchValue] = useState<string>('')

我在运行时得到一个错误:CCD_ 2。

我搞不清楚出了什么问题。无论我在哪里检查,他们都建议像我上面所做的那样定义状态类型。

以下是我的打字脚本配置:

{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"noImplicitAny": true,
"allowSyntheticDefaultImports": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}

我没有webpack配置,因为它们与Nextjs一起提供(已经配置为使用typescript(

我确实安装了@types/react @types/react-dom @types/node

有什么提示吗?

事实证明,我的babel.config.json中存在一些不匹配的配置

我删除了所有内容,只保留了这些行:

{
"presets": ["next/babel"],
"env": {
"test": {
"presets": ["next/babel"]
}
}
}

通过这种方式,我仍然可以运行我的Jest测试。

希望它能对这种情况下的其他人有所帮助:(

最新更新