【问题标题】:How to fix the Rendered more hooks than during the previous render using react hook如何使用 React hook 修复渲染的钩子比上一次渲染时更多的钩子
【发布时间】:2021-04-06 15:20:23
【问题描述】:

index.tsx

   import useUser from '@services/users';
    import React, { useState, useEffect } from 'react';
    import { useTranslation } from 'react-i18next';

function App() {
      const { t } = useTranslation();
    
      const { getAll } = useUser();
      const [ rowData, setRowData ] = useState([]);
    
     useEffect(() => {
        let ignore = false;
        (async function setAllData() {
          let response = await getAll({ length: 9999 });
        })()
        if (!ignore) {
            setRowData(response['data']['data']);
          }
        })()
        return () => {
          ignore = true;
        }
      }, [])
    
     return (
        <>
          <button>{t('create')}</button>
          {
            rowData.map((item, index) => (
              <div key={index}>
                {item.firstName}<br/>
              </div>
            ))
          }
        </>
      )
    }
    export default App;

user.tsx

export default function useUser() {
 const creds = useCredentials();

  Axios.defaults.baseURL = serverConfig[creds.server].api;
  
  return {

    getAll: (params?: object) => Axios.get(API_URL + (params ? getQueryParams(params) : ''))
    }

    }

我在添加 react-i18next(即 useTranslation)时遇到了问题。错误消息是 Rendered more hooks than during the previous render.添加翻译时。我该如何解决?

【问题讨论】:

  • 这是完整的代码吗?错误消息通常表明您正在有条件地调用反应钩子。
  • 您发布的代码不包含导致它的部分。
  • @trixn 是的,当我尝试删除 useTranslation()react-i18next 时,没有错误。但我需要使用 useTranslation
  • useEffect / useAnyHook 需要在函数内部。我不使用 Next.js,但我觉得它必须将您的代码自动包装到一个返回 JSX 的函数中,如果它没有导致返回错误的话。所以我建议将你得到的代码包装到另一个函数中,useEffect 等可以看到按顺序运行,以防 next.js 有某种安装副作用。
  • @trixn 是的,试图弄清楚无效的 JS 语法是如何工作的。 OP 现在已经添加了缺失的代码,所以现在更有意义了。

标签: javascript reactjs typescript react-hooks


【解决方案1】:

我在 useTranslation 上遇到了同样的问题。 对我来说,原因是将 i18next 初始化脚本包装在一个调用 App.tsx 内部的函数中,而不是仅导出 i18n 并将其直接导入 index.tsx 中

所以不是:

App.tsx

import initI18n from './i18n.ts'

const App = () => {
  initI18n()
  return <div>Party</div>
}

但这行得通

index.tsx

import './i18n.ts'

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 2019-12-24
    • 2021-10-12
    • 2021-02-09
    • 2021-11-02
    • 2021-01-06
    • 2019-10-02
    • 2020-05-26
    相关资源
    最近更新 更多