React 18中useState生成的Setter非函数报错问题求助
问题原因及解决方案
问题出在useState的解构方式上——useState返回的是数组,不是对象,你误用了对象解构({}),正确做法是用数组解构([])。
数组解构是按位置匹配值,而对象解构需要严格匹配键名。useState返回的数组里只有两个元素:第一个是状态值,第二个是setter函数,它们没有SetBrandVisible这类属性名,所以用对象解构时,你的SetBrandVisible会被解析成undefined,调用undefined()自然会触发“不是函数”的报错。
修正后的代码:
const AdminPanel = () => { const [brandVisible, setBrandVisible] = useState(false) const [typeVisible, setTypeVisible] = useState(false) const [dyeVisible, setDyeVisible] = useState(false) return ( <Container className="d-flex flex-column"> <Button variant="outline-dark" onClick={()=> setTypeVisible(true)} className="mt-2 p-1">Добавить тип</Button> <Button variant="outline-dark" onClick={()=> setBrandVisible(true)} className="mt-2 p-1">Добавить производителя</Button> <Button variant="outline-dark" onClick={()=> setDyeVisible(true)} className="mt-2 p-1">Добавить краску</Button> <CreateBrand show={brandVisible} onHide={()=> setBrandVisible(false)}/> <CreateDye show={dyeVisible} onHide={()=> setDyeVisible(false)}/> <CreateType show={typeVisible} onHide={()=> setTypeVisible(false)}/> </Container> ); }
顺便提一句:React的命名惯例里,setter函数一般用小驼峰写法(比如setBrandVisible),这不是报错的原因,只是规范建议。
内容的提问来源于stack exchange,提问作者zavaryxa
相关产品推荐
相关产品推荐

