在React中调用两个useState的setter会引发错误。为什么?

8 浏览
0 Comments

在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还不熟悉,肯定有些地方我没有注意到。

0
0 Comments

在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 (
Suman
{JSON.stringify(data)}
); } export default App;

或者你可以像从命名模块导入一样导入。命名模块可以使用import { exportName } from 'module'导入;

为了更好地理解默认导出和命名导出,请阅读这个回答

0
0 Comments

在React中使用两个useState设置器会导致错误的原因是没有为setData use state指定默认状态值。需要在使用useState hook时指定默认状态值,就像我们使用的那样。尝试使用下面的代码更改setData行。这里,我们将默认状态值指定为空对象。

解决方法:

const [data, setData] = useState({});

原因:

没有为setData use state指定默认状态值。需要在使用useState hook时指定默认状态值。

0