const-iterator 相关问题


为什么将迭代器 '(vector<int> a).begin()' 传递给参数 'vector<T>::iterator b' 时无法推断 'T' 的类型?

有以下代码: 模板 void test(const typename std::vector::iterator &i){ } int main(int argc, char **argv) { std::向量 a; 测试(a.


如何查找给定的键是否存在于 std::map 中

我正在尝试检查给定的键是否在地图中,但有些无法做到: typedef 映射::迭代器 mi; 地图米; m.insert(make_pair("f","++--")); 一对 我正在尝试检查给定的键是否在地图中,但有些做不到: typedef map<string,string>::iterator mi; map<string, string> m; m.insert(make_pair("f","++--")); pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want cout << p.first;//I'm getting error here 那么我怎样才能打印p中的内容呢? 使用 map::find 和 map::end: if (m.find("f") == m.end()) { // not found } else { // found } 要检查映射中是否存在特定键,请通过以下方式之一使用 count 成员函数: m.count(key) > 0 m.count(key) == 1 m.count(key) != 0 map::find的文档说:“另一个成员函数map::count可用于仅检查特定键是否存在。” map::count的文档说:“因为地图容器中的所有元素都是唯一的,所以该函数只能返回1(如果找到该元素)或零(否则)。” 要通过您知道存在的键从映射中检索值,请使用 map::at: value = m.at(key) 与 map::operator[] 不同,如果指定的键不存在,map::at 不会在映射中创建新键。 C++20 为我们提供了 std::map::contains 来做到这一点。 #include <iostream> #include <string> #include <map> int main() { std::map<int, std::string> example = {{1, "One"}, {2, "Two"}, {3, "Three"}, {42, "Don\'t Panic!!!"}}; if(example.contains(42)) { std::cout << "Found\n"; } else { std::cout << "Not found\n"; } } 您可以使用.find(): map<string,string>::iterator i = m.find("f"); if (i == m.end()) { /* Not found */ } else { /* Found, i->first is f, i->second is ++-- */ } C++17 通过带有初始化器的 If 语句进一步简化了这一点。 这样你就可以鱼与熊掌兼得了。 if ( auto it{ m.find( "key" ) }; it != std::end( m ) ) { // Use `structured binding` to get the key // and value. const auto&[ key, value ] { *it }; // Grab either the key or value stored in the pair. // The key is stored in the 'first' variable and // the 'value' is stored in the second. const auto& mkey{ it->first }; const auto& mvalue{ it->second }; // That or just grab the entire pair pointed // to by the iterator. const auto& pair{ *it }; } else { // Key was not found.. } m.find == m.end() // not found 如果您想使用其他API,请找到m.count(c)>0 if (m.count("f")>0) cout << " is an element of m.\n"; else cout << " is not an element of m.\n"; 我想你想要map::find。如果 m.find("f") 等于 m.end(),则未找到密钥。否则,find 返回一个指向找到的元素的迭代器。 错误是因为p.first是一个迭代器,它不适用于流插入。将最后一行更改为 cout << (p.first)->first;。 p 是一对迭代器,p.first 是迭代器,p.first->first 是键字符串。 一张地图对于给定的键只能有一个元素,所以 equal_range 不是很有用。它是为映射定义的,因为它是为所有关联容器定义的,但它对于多重映射更有趣。 template <typename T, typename Key> bool key_exists(const T& container, const Key& key) { return (container.find(key) != std::end(container)); } 当然,如果你想变得更奇特,你可以随时模板化一个函数,该函数也采用已找到的函数和未找到的函数,如下所示: template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction> void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function) { auto& it = container.find(key); if (it != std::end(container)) { found_function(key, it->second); } else { not_found_function(key); } } 并像这样使用它: std::map<int, int> some_map; find_and_execute(some_map, 1, [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; }, [](int key){ std::cout << "key " << key << " not found" << std::endl; }); 这样做的缺点是想出一个好名字,“find_and_execute”很尴尬,我想不出更好的名字...... map<string, string> m; 检查 key 是否存在,并返回出现次数(map 中为 0/1): int num = m.count("f"); if (num>0) { //found } else { // not found } 检查key是否存在,并返回迭代器: map<string,string>::iterator mi = m.find("f"); if(mi != m.end()) { //found //do something to mi. } else { // not found } 在你的问题中,由坏的operator<<过载引起的错误,因为p.first是map<string, string>,你无法打印出来。尝试这个: if(p.first != p.second) { cout << p.first->first << " " << p.first->second << endl; } 小心地将查找结果与地图“m”的结尾进行比较,因为所有答案都有 上面完成 地图::迭代器 i = m.find("f"); if (i == m.end()) { } else { } 您不应该尝试执行任何操作,例如如果迭代器 i 等于 m.end() 则打印键或值,否则会导致分段错误。 比较 std::map::find 和 std::map::count 的代码,我认为第一个可能会产生一些性能优势: const_iterator find(const key_type& _Keyval) const { // find an element in nonmutable sequence that matches _Keyval const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound return (_Where == end() || _DEBUG_LT_PRED(this->_Getcomp(), _Keyval, this->_Key(_Where._Mynode())) ? end() : _Where); } size_type count(const key_type& _Keyval) const { // count all elements that match _Keyval _Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower. size_type _Num = 0; _Distance(_Ans.first, _Ans.second, _Num); return (_Num); } find() 和 contains() 都可以使用。根据文档。两种方法平均时间为常数,最坏情况下为线性时间。 我知道这个问题已经有一些很好的答案,但我认为我的解决方案值得分享。 它适用于 std::map 和 std::vector<std::pair<T, U>>,并且可从 C++11 开始使用。 template <typename ForwardIterator, typename Key> bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) { using ValueType = typename std::iterator_traits<ForwardIterator>::value_type; auto search_result = std::find_if( first, last, [&key](ValueType const& item) { return item.first == key; } ); if (search_result == last) { return false; } else { return true; } } map <int , char>::iterator itr; for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++) { if (itr->second == 'c') { cout<<itr->first<<endl; } } 如果你想比较成对的地图,你可以使用这个方法: typedef map<double, double> TestMap; TestMap testMap; pair<map<double,double>::iterator,bool> controlMapValues; controlMapValues= testMap.insert(std::pair<double,double>(x,y)); if (controlMapValues.second == false ) { TestMap::iterator it; it = testMap.find(x); if (it->second == y) { cout<<"Given value is already exist in Map"<<endl; } } 这是一项有用的技术。


为什么 Iterator<Item = T> 和 Iterator<Item = &T> 的实现会发生冲突?

此代码无法编译: 酒吧特质 ToVec { fn to_vec(self) -> Vec; } 为 I 实现 ToVec 在哪里 我:迭代器, { fn to_vec(self) ...


resourcemanager.NewProjectsClient().ListProjects() 的迭代器在 GCP 中无法按预期工作

用于存储的 google.golang.org/api/iterator 似乎按预期工作 — 我能够循环超过 6K 的存储桶对象。然而,当在项目中使用 google.golang.org/api/iterator 时,我只得到 3


将生成器函数注释为迭代器的混乱

Python 类型文档中写道: 或者,将生成器注释为具有 Iterable[YieldType] 或 Iterator[YieldType] 的返回类型: def infinite_stream(开始: 我...


如何在 Rust 中包含 dyn Iterator 的结构体上实现 Clone? [重复]

我在 Rust 中有以下结构: #[派生(克隆)] pub 结构方程迭代器 { 柜台:盒子>, 公式:圆弧方程...


询问正确的SQL查询

const personid = result.map(item => item.person_id) console.log("personen", personid) const formattedid = personid.join(","); const nameResult = 等待


为什么const指针可以指向非常量对象?

//示例1 常量双饼 = 3.14; // 常量对象 const double *cptr = &pie; // 指向 const 对象的指针 双 *ptr = &pie; // 错误 - 指向 const 的非 const 指针 //


Flutter Hive 更新

返回ListTile( tileColor:组件颜色, 前导:图标按钮( 图标:widget.isDone? const Icon(Icons.check_box) : const Icon(Icons.check_box_outline_blank), 颜色:


自定义骑行存在(discord.js v14)

const 猫鼬 = require("猫鼬") 需要(“dotenv”).config() const {Client,ActivityType} = require("discord.js") 模块. 导出 = { 名称:'准备好', /** ...


scryRenderedComponentsWithType 返回一个空数组

我对 React 应用程序进行了以下测试: it('有 7 个 NavBarItems', () => { const 组件 = ReactTestUtils.renderIntoDocument(); const navBarItems = ReactTestUtils.


我可以有一个同时接受 const-ref 和非 const-ref 指针的 C++ 方法吗?

我有一些辅助方法,它们通过引用接受指针,如果满足某些条件,则将其向前推进。这是一个例子: char32_t readCodePoint(const char8_t *¤t, const char...


类模板针对 const 和非 const 指针的部分特化

我正在尝试制作一个具有指针类型的非类型模板参数的类模板,它有 const 和非 const 指针的两个特化。 这是我最好的尝试,被 Clang 接受并......


如何将 const 添加到指向类型?

假设我有一个类模板: 模板 结构A { T值; 无效 foo(自动乐趣) { 乐趣(价值); // ^^^^^^^ 将值作为 const 对象传递 } }; 我想将 const 添加到 v...


{;} 和 (,) 有什么区别? [重复]

在 React.js 中,将函数或常量编写为 const aHandler = () => {function1() ;函数2();} 与 const aHandler = () => (函数 1() , 函数 2()) 从...


我正在尝试使用 Fluent-ffmpeg 合并视频,但有时它会合并视频,但每当我们第二次尝试合并视频时,它都会显示错误

const express =require('express') 常量应用程序 = Express() const ffmpeg = require('流畅的 ffmpeg') const ffmpegPath = require('@ffmpeg-installer/ffmpeg') const ffprobe = require('@ffprobe-installer/ff...


Discord.js 聊天机器人

请帮助我。这是我下面关于discord.js 聊天机器人的代码 const fetch = require("node-fetch"); const {ChannelType} = require("discord.js"); client.on('messageCreate...


Node Express.js 应用程序在本地运行良好,但在 Docker 中显示“无法获取/”

我在 Node 应用程序中定义了一个 Express.js 服务器,如下所示: const express = require('express') const SignRequest = require('./SignRequest/lambda/index.js') const VerifyResponse = require('./


浏览器未实现Geolocation.requestPermissions,并且错误始终未被捕获?

从“@capacitor/geolocation”导入{地理位置}; const request_perm = () => { 尝试 { const stuff = Geolocation.requestPermissions(); console.log(东西,“东西&


整数转换为指针是什么意思?

给出以下代码: 令 mut a = 5; 设 b = &mut a; *b = 6; println!("{:p}",&a as *const i32 ); println!("{:p}",a as *const i32 ); println!("{:p}",&a); 原则...


Chai returnedWith 未正确链接

我已经阅读了大量的帖子和文档,但似乎无法弄清楚为什么这段代码不能像我认为的那样工作。 const chai = require('chai'); const 期望 = chai.expect; const chaiAsPromised = r...


函数后面的const如何优化程序? [重复]

我见过一些这样的方法: void SomeClass::someMethod() const; 这个 const 声明有什么作用,它如何帮助优化程序? 编辑 我看到这个问题的第一部分...


如何创建松果客户端,它给出错误

存在于松果.ts 中 从 '@pinecone-database/pinecone' 导入 { PineconeClient } 导出 const getPineconeClient = async () => { const client = new PineconeClient() 等待客户。


使用 vanilla-extract 和 esbuild 导入图像

我在使用 vanilla-extract 和 esbuild 导入图像时遇到问题 我的构建文件: const { build } = require("esbuild"); const { vanillaExtractPlugin } = require("@vanilla-extract/


类型错误:无法读取 <img/> 标记中未定义的属性(读取“0”)

从“react”导入React; const DataPage = ({ 数据 }) => { const dataList = 数据; 控制台.log(数据列表); 返回 (


文件大小错误节点js

从大文件下载 25mb 小块时,这些块实际上比 25mb 大得多。有人可以帮忙吗? const fs = require('fs') const 文件 = fs.readdirSync('../in/') 文件.map(


React Js - {;} 和 (,) 有什么区别? [重复]

这可能是一个非常菜鸟的问题。但是在 ReactJs 中,将函数或常量编写为 const aHandler = () => { 函数 1 ;函数2;} 与 const aHandler = () => (


这里是否误报:警告C4172:返回局部变量或临时变量的地址?

在以下代码中: #包括 #包括 模板 类索引{ 民众: const std::string& 文本; const std::向量&...


是否使用 useState 来反应原生动画 => new Animated.Value() ?

在react-native中使用Animated.Value()的最佳方法是什么? 是否使用 useState() ? const [fadeAnim] = useState(new Animated.Value(0)) 或者 const fadeAnim = new Animated.Value(0) React-nati...


在 onCompleted 执行之前加载状态更新会导致内容闪烁

我目前的 React 组件中有这个突变: 从 '@remix-run/react' 导入 { useNavigate } ... const MyComponent = () => { const { 重定向到 } = useNavigate(); ... 常量 [


如何解决加载响应数据失败:未找到具有给定标识符的资源的数据

发布API 导出 const resendInvitation = async (userName) => { wait API.post( 'delta-api',user-mgmt/users/${userName}/resendInvitation, {} ); }; const handleResendInvitation = async () =>...


MUI-table:mui 表组件中交替行的不同颜色不起作用

为备用表格行添加不同的颜色不起作用 函数行(道具){ const { 行 } = 道具; const StyledTableRow = styled(TableRow)(({ 主题 }) => ({ '&:第 n 个类型...


为什么没有从指针到引用的隐式转换到const指针[重复]

我将用代码来说明我的问题: #包括 void PrintInt(const unsigned char*& ptr) { 整数数据=0; ::memcpy(&data, ptr, sizeof(data)); // 推进 po...


C++ 中的“const class <class_name>&”是什么?

我在Ardupilot代码中偶然发现了这个成员函数声明: void update(const class Aircraft &aircraft) override; 您可以在他们的代码库中随处看到它:链接 什么是


未捕获的类型错误:Promise.reject 不是构造函数[已关闭]

我遇到了问题; const p4 = new Promise.reject("错误"); 或者 const p4 = new Promise.resolve("成功"); 我在定义时遇到这样的错误; 未捕获的类型错误:Promise.reject ...


如何从 const boost::multi_array 获取特定元素

我想知道如何从 const boost::multi_array 对象中读取元素。 事实上,据我所知,我不能使用运算符 [],因为它也用于赋值。 我有一个 3D 维度...


如何控制列表元素抛出键盘事件

https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 <div> <input onChange={handleSearchChange}/> <div css={countryDataCss}> {countryList?.map((country) => ( <div key={country.countryCode}> <span css={countryCss}>{country.countryName}</span> <span css={countryDialCodeCss}> {country.countryDialNo} </span> </div> ))} </div> </div> 您可以使用 javascirpt 事件 onkeydown,对于 React 来说是 onKeyDown,它提供了所需的行为,请检查下面的 stackblitz! import React from 'react'; import './style.css'; import { useState } from 'react'; export default function App() { const [searchText, setSearchText] = useState(''); const [selectedCountry, setSelectedCountry] = useState('SG'); const [activeIndex, setActiveIndex] = useState(0); const [selectedDialCode, setSelectedDialCode] = useState('+65'); const countryCodeListResponse = [ { countryCode: 'IND', countryDialNo: '+91', countryName: 'India' }, { countryCode: 'SG', countryDialNo: '+65', countryName: 'Singpare' }, ]; const [countryList, setCountryList] = useState(countryCodeListResponse); function handleSearchChange(e) { const searchText = e.target.value.toLowerCase(); if (countryCodeListResponse) { const updatedList = countryCodeListResponse .filter((el) => el.countryName.toLowerCase().includes(searchText)) .sort( (a, b) => a.countryName.toLowerCase().indexOf(searchText) - b.countryName.toLowerCase().indexOf(searchText) ); setSearchText(searchText); setCountryList(updatedList); } } const onSelectCountry = (code, dialCode) => { setSelectedCountry(code); setSelectedDialCode(dialCode); setSearchText(''); setCountryList(countryCodeListResponse); }; const onKeyDown = (event) => { console.log(event); switch (event.keyCode) { case 38: // arrow up if (activeIndex > 0 && activeIndex <= countryList.length - 1) { setActiveIndex((prev) => prev - 1); } break; case 40: // arrow down if (activeIndex >= 0 && activeIndex < countryList.length - 1) { setActiveIndex((prev) => prev + 1); } break; case 13: const country = countryList[activeIndex]; onSelectCountry(country.countryCode, country.countryDialNo); break; default: break; } }; return ( <div class="dropdown"> <div class="search"> <div> <span>{selectedCountry}</span> <span>{selectedDialCode}</span> </div> <input class="search-input" onKeyDown={(e) => onKeyDown(e)} placeholder="Search" value={searchText} onChange={handleSearchChange} /> </div> <div class="list"> {countryList?.map((country, index) => ( <div onKeyDown={(e) => onKeyDown(e)} className={index === activeIndex ? 'active' : ''} tabIndex="0" key={country.countryCode} onClick={() => onSelectCountry(country.countryCode, country.countryDialNo) } > <span>{country.countryName}</span> <span>{country.countryDialNo}</span> </div> ))} </div> </div> ); } 堆栈闪电战


“const int*”类型的值不能用于初始化“int* const”类型的实体

我在 vs 2022 社区版本上有 c++ 代码。 导入标准; int main() { constexpr int x = 10; constexpr int* p = &x; } 我不允许将 x 的地址分配给 p


如何在 RegExp javascript 中排除搜索词中的逗号

我有字符串: const text = 'A Jack# Jack#aNyWord Jack,Jack'; 我只想搜索单词“Jack”,但如果 Jack 包含 # 字符,则表示真正的均值匹配。 我尝试像: const text = 'A Jack#...


react-hook-form useForm 每次在 Nextjs 页面路由上执行

嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 然而,似乎每次都会执行useForm,并且defaultValues是在页面路由中设置的(点击 嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 不过,好像每次都会执行useForm,并且在页面路由时设置defaultValues(点击<Link to=XX>)。 如何跨多个页面保存表单数据? 请帮助我。 这是我的代码。 _app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ); FormProvider.tsx export const FormProvider = ({ children, }: { children: React.ReactNode; }) => { const defaultValues: MyForm = { name: '', description: '' }; const form = useForm({ defaultValues, resolver: zodResolver(MyFormSchema), }); const onSubmit = () => console.log("something to do"); return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}>{children}</form> </Form> ); }; 您正在寻找的是跨多个页面维护的某种全局状态。对于这个例子,我将使用 React 的上下文 API,如果这不适合您的用例,您可以找到一些其他状态管理库。 首先,您需要创建一个全局上下文,并在表单提供程序中包含一个全局状态 // FormProvider.tsx import { createContext, useContext, useState } from 'react'; const FormContext = createContext(); // Exported to be used in other components export const useFormContext = () => useContext(FormContext); export const FormProvider = ({ children }) => { const [formData, setFormData] = useState({}); return ( <FormContext.Provider value={{ formData, setFormData }}> {children} </FormContext.Provider> ); }; 现在您需要用 FormProvider 包装您的应用程序 // You are already doing this part //_app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ) 现在你可以像这样使用它了。请记住,您将更新表单的全局状态,该状态将在您的所有页面上发生变化。 // In your form component import { useForm } from 'react-hook-form'; import { useFormContext } from '../path/to/formContext'; const MyFormComponent = () => { const { formData, setFormData } = useFormContext(); const { register, handleSubmit } = useForm({ defaultValues: formData, resolver: zodResolver(MyFormSchema), }); const onSubmit = (data) => { setFormData(data); // Handle form submission }; return ( <form onSubmit={handleSubmit(onSubmit)}> {/* Form fields */} </form> ); }; 您可以从其他页面访问数据的示例 // In another page or component import { useFormContext } from '../path/to/formContext'; const AnotherPage = () => { const { formData } = useFormContext(); // Use formData as needed };


在React中不显示服务器上的图像

这是代码 从“反应”导入反应; 从“react-dom/client”导入ReactDOM; const 标头 = () => { 返回 ( <... 这是代码 import React from "react"; import ReactDOM from "react-dom/client"; const Header = () => { return ( <div className="header"> <div className="logo-container"> <img className="logo" src="/assets/logo.jpg" /> </div> <div className="nav-items"> <ul> <li>Home</li> <li>About us</li> <li>Contact us</li> <li>Cart</li> </ul> </div> </div> ); }; const AppLayout = () => { return ( <div className="App"> <Header /> </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<AppLayout />); 请帮助我,因为我是新反应。 我期待在服务器上显示图像 如果仍然不起作用,请尝试在上面的代码中添加 alt 标签 试试这个: 从“react”导入React; 从“react-dom/client”导入 ReactDOM; const Header = () => { return ( <div className="header"> <div className="logo-container"> <img className="logo" src={process.env.PUBLIC_URL + "/assets/logo.jpg"} alt="Logo" /> </div> <div className="nav-items"> <ul> <li>Home</li> <li>About us</li> <li>Contact us</li> <li>Cart</li> </ul> </div> </div> ); }; const AppLayout = () => { return ( <div className="App"> <Header /> </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<AppLayout />);


我需要用非常量元素锁定 const 容器吗?

我开发了一个多线程应用程序(用 C++ 开发),它具有各种集合,其中容器(向量、映射等)在初始化时是 const,但容器中的元素...


如何在添加间隔的同时在获取请求中使用超时来停止轮询

我正在轮询我的报告,并在每个请求之间添加 5 秒的间隔。 const addDelay = 超时 => 新 Promise(resolve => setTimeout(resolve, timeout)) 导出 const myReport = () => a...


在使用 TypeScript 进行 React 时,输入字段在“值”处给出错误

从“react”导入{SetStateAction,useState} const 登录表单 =() =>{ const [名称,setName] = useState(); const [全名,setFullname] = useState import { SetStateAction, useState } from "react" const Loginform =() =>{ const [name, setName] = useState<String | null>(); const [fullname, setFullname] = useState<String | null>(); const inputEvent =(event: { target: { value: SetStateAction< String |null | undefined >; }; })=>{ setName(event.target.value) } const Submit = ()=>{ setFullname(name) } return <> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> <button onClick={Submit}>Submit</button> <h1>Hi {fullname==null? "Guest" :fullname}</h1> </> } export default Loginform <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> 上一行中的“value”属性显示错误 这是错误详细信息: (property) React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined Type 'String | null | undefined' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'null' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322) index.d.ts(2398, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>' 也尝试写 return as any。或者尝试添加 string[],但出现错误。 进行以下调整: 将 String 替换为 string,因为原始 Typescript 类型是小写的 (number, string, boolean, etc) TypeScript 报告此错误,因为属性值不接受 null 作为值,而是接受 undefined。将代码更新为: const [name, setName] = useState<string>() 这会使用 string 作为默认类型来初始化状态。 初始状态隐式地被视为 undefined,因为如果未显式提供,TypeScript 会将类型的默认值设置为 undefined。 为了简单起见,您不需要解构事件。使用内联函数,如下例所示: <input type="text" placeholder="Enter your name" onChange={(e) => setName(e.target.value)} value={name}/> 我使用你的代码创建了一个 CodeSanbox,它似乎只需要很少的修改就可以正常工作。 您可以在这里找到沙盒 这是我想出的代码 import { SetStateAction, useState } from "react"; const Loginform = () => { const [name, setName] = useState<string | null>(); const [fullname, setFullname] = useState<string | null>(); const inputEvent = (event: { target: { value: SetStateAction<string | null | undefined> }; }) => { setName(event.target.value); }; const Submit = () => { setFullname(name); }; return ( <div> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name} /> <button onClick={Submit}>Submit</button> <h1>Hi {fullname == null ? "Guest" : fullname}</h1> </div> ); }; export default Loginform;


React 中 fetch 调用后的清理函数

const[imageContainer,setImageContainer] = useState([]) 常量导航 = useNavigate(); 使用效果(()=>{ Promise.all([ fetch("https://www.themealdb.com/api/json/v1/1/


React,useCallback更新了一个状态变量,该变量也存在于其依赖数组中,它如何防止无限重新渲染?

考虑以下代码 从 'react' 导入 { useMemo, useState, useCallback } 函数应用程序(){ const [count, setCount] = useState(0); const handleClick = useCallback(() => { 设置公司...


const 泛型和 `typenum` 箱子有重叠的目的吗?

在了解了 const 泛型并偶然发现了 typenum 箱子之后,我对它们似乎有重叠的目的这一事实感到困惑 - 使用数值作为类型。 唯一不同的是...


为什么我有很多对 API 的请求,需要在 next.js 13v 的服务器端获取数据

我使用 Next.js 13v 在服务器端获取数据。 我的组件 const 页脚 = async () => { // 获取数据 const allCategories = (await getAllCategories({})).data; 返回 我使用 Next.js 13v 在服务器端获取数据。 我的组件 const Footer = async () => { // Get data const allCategories = (await getAllCategories({})).data; return <footer className={styles.footer}></footer>; }; 我的功能 export const getAllCategories = async ( params: IGetAllCategoriesRequest, ): Promise<AxiosResponse<IGetAllCategoriesResponse>> => { const url = 'static-pages/category/public'; const response = await axiosInstance.get<IGetAllCategoriesResponse>( url, { params: params, }, ); return response; }; 如果请求成功,我有一个请求 但是如果出现错误,我有很多请求,然后重定向到错误页面 本机获取具有相同的行为 那么为什么我在 next.js 13v 中对 API 有很多请求并在服务器端获取数据? 可能和开发模式有关。我发现这篇文章可能与此行为有关:https://dev.to/noclat/fixing-too-many-connections-errors-with-database-clients-stacking-in-dev-mode-with-next -js-3kpm


C 和 C++ 的常量正确性有什么区别?

我理解 const 正确性意味着什么,我的问题不是关于 const 正确性是什么。所以我不期待对此的解释或 C++-FAQ 链接。 我的问题是: 这些是什么...


mongodb+srv URI 不能有端口号

我有(注:用户名和密码是虚构的): const CONNECTION_URL = "mongodb+srv://smith_bob:[email protected]:T@llyHo!:@cluster0.r92qc.mongodb.net/myFirstDatabase?retryWrites=true&am...


© www.soinside.com 2019 - 2024. All rights reserved.