【问题标题】:Running into an infinite loop when using useEffect() in react-native在 react-native 中使用 useEffect() 时陷入无限循环
【发布时间】:2020-03-22 21:57:10
【问题描述】:

我最近开始使用 react native,我正在使用 Expo 构建这个移动应用程序。我正在使用useEffect() 来调用其中的函数。我想要的只是等待 API 的响应完全完成,然后再显示结果(在本例中为 connectionName 变量)。我将useEffect() 函数wallets 作为第二个参数,因为我希望每当wallets 更改时再次获取API,但即使wallets 没有更改,我似乎也在无限循环中运行。非常感谢任何帮助。

export default function LinksScreen() {

       const [wallets, setWallets] = React.useState([]);
       const [count, setCount] = React.useState(0);
       const [connectionName, setConnectionName] = React.useState("loading...");

       React.useEffect(() => {
          (async () => {
             fetchConnections();
          })();
       }, [wallets]);

       async function fetchConnections() {

          const res = await fetch('https://api.streetcred.id/custodian/v1/api/' + walletID + '/connections', {
             method: 'GET',
             headers: {
                Accept: 'application/json',
             },
          });
          res.json().then(res => setWallets(res)).then(setConnectionName(wallets[0].name))
       }

       return (
          <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
             <OptionButton
                icon="md-school"
                label={connectionName}
                onPress={() => WebBrowser.openBrowserAsync('https://docs.expo.io')}
             />
          </ScrollView>
       );
    }

【问题讨论】:

  • useEffect 挂钩将在每次依赖关系数组中的依赖项发生更改时重新运行。如果你的钩子中的函数改变了依赖关系,它将永远循环。

标签: reactjs react-native expo infinite-loop


【解决方案1】:

每次wallets 更改时,您的useEffect 挂钩都会运行,它会调用fetchConnections,后者会调用setWallets,然后会触发您的useEffect 挂钩,因为它更改了wallets,等等...

将一个空的依赖数组传递给 useEffect:

React.useEffect(() => {...}, [])

这将使它只在挂载时运行。

如果您仍想在wallets 更改时调用fetchConnections,则不应通过效果挂钩来执行此操作,因为您将获得所描述的无限循环。相反,每当您调用setWallets 时,请手动调用fetchConnections。您可以为您创建一个函数:

const [wallets, setWallets] = useState([]);
const setWalletsAndFetch = (wallets) => {
  setWallets(wallets);
  fetchConnections(wallets);
} 

【讨论】:

  • 我尝试使用“setWalletsAndFetch”,但在相同的无限循环中得到了相同的结果,是的,我正在尝试做的是在钱包发生变化时调用 fetchConnections。
【解决方案2】:

你聆听一个变化,然后随着它的变化你一遍又一遍地改变它而不停止

 React.useEffect(() => {
          (async () => {
             fetchConnections();
          })();
       }, []);//remove wallets

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 2020-02-21
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2020-04-14
    相关资源
    最近更新 更多