在React中调用两个useState的setter会引发错误。为什么?
在React中调用两个useState的setter会引发错误。为什么?
我有一个功能组件:
export const Special = (props) => { const [data, setData] = useState(); const [loading, setLoading] = useState(true); const dataRead = (dt) => { setData(dt); setLoading(false); } useEffect(() => { setLoading(true); fetch("/reportTypes/search/visible") .then( (response) => response.json() ) .then( dataRead) .catch( (err) => { setLoading(false); }); }, []); if ( loading ) return (); return ( {JSON.stringify(data)} ); }
如果我从dataRead方法中删除setData(dt)或setLoading(false)中的一个,它就能正常工作。但是,如果两者都存在,我会得到一个错误:
Uncaught Error: Element type is invalid: expected a string (for
built-in components) or a class/function (for composite components)
but got: undefined. You likely forgot to export your component from
the file it's defined in, or you might have mixed up default and named
imports.
我尝试在不使用useEffect的情况下调用它 - 结果相同。我尝试了上述带方括号和不带方括号的useEffect。我尝试了各种配置。无论如何,调用setData和setLoading都会导致此错误。删除其中一个使其正常运行。我对React还不熟悉,肯定有些地方我没有注意到。
在React中调用两个useState的setter会导致错误。这个问题出现的原因是在使用Special组件的地方,你将其作为普通的导入方式引入,例如import Special from 'module'
,但你没有将其作为默认导出。也就是说,你混淆了默认导出和命名导入,这就是你在这里得到一个非常明确的错误信息的原因:
你可能忘记从定义它的文件中将组件导出,或者你可能混淆了默认导出和命名导入。
尝试将你的命名导出替换为默认导出,像下面这样:
import React from 'react'; import {useState, useEffect} from 'react'; const App = (props) => { const [data, setData] = useState(); const [loading, setLoading] = useState(true); const dataRead = (dt) => { setData(dt); setLoading(false); } useEffect(() => { setLoading(true); fetch("/reportTypes/search/visible") .then( (response) => response.json() ) .then( dataRead) .catch( (err) => { setLoading(false); }); }, []); if ( loading ) return (Ankita); return (); } export default App;Suman{JSON.stringify(data)}
或者你可以像从命名模块导入一样导入。命名模块可以使用import { exportName } from 'module'
导入;
为了更好地理解默认导出和命名导出,请阅读这个回答。