首页 > 解决方案 > 如何正确缓解 reactjs 中的无效钩子问题

问题描述

我正在尝试使用reactjsairtable.com显示我的记录,但它会引发错误

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
 This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我在这里找到了参考解决方案 链接

我将 Rec 类更改为功能,然后尝试将其导出,但仍无法使其正常工作

这是代码

import {initializeBlock, useBase, useRecords} from '@airtable/blocks/ui';
import React, { Component } from "react";
import ReactDOM from 'react-dom';

class Rec extends React.Component{
    constructor(props) {
        super(props);

        this.state = {
            id: ''
        };
    }


myRecords() {
alert('ok');

 const base = useBase();
 const table = base.getTableByNameIfExists('myfirst_table');
 // grab all the records from that table
 const records = useRecords(table);
// render a list of records:
     return (
         <ul>
             {records.map(record => {
                 return <li key={record.id}>{record.id} </li>
             })}
         </ul>
     );


    render() {
        return (
          <div>
             <h2>My Records</h2>

{this.myRecords()}
          </div>
        );
    }
}

export default Rec;

用先生的解决方案更新了部分。哈盖

class Rec extends React.Component{
    constructor(props) {
        super(props);

        this.state = {
            id: ''
        };
    }


myRecords() {
alert('ok');
 //const base = useBase();
 //const table = base.getTableByNameIfExists('myfirst_table');
 // grab all the records from that table
 //const records = useRecords(table);
// render a list of records:
     return (
         <ul>
             {records.map(record => {
                 return <li key={record.id}>{record.id} </li>
             })}
         </ul>
     );

 }
    render() {
        return (
          <div>
             <h2>Hello welcome to contact page</h2>


 {this.myRecords()}
          </div>
        );
    }
}

export default () => {
    const base = useBase();
    const table = base.getTableByNameIfExists('myfirst_table');
    const records = useRecords(table);
    return <Rec base={base} records={records} />
}
//export default Rec;

标签: reactjs

解决方案


useBase并且useRecords不能在类组件中调用钩子,但是您可以采取一些解决方法来避免通过将传递baserecords作为道具的导出箭头函数重写代码

class Rec extends React.Component{
  ...rest class without useBaes() and useRecords() assiganing... 
}

export default (props) => {
    const base = useBase();
    const table = base.getTableByNameIfExists('myfirst_table');
    const records = useRecords(table);
    return <Rec {...props} base={base} recoreds={records} />
}

现在base可用,this.props.base并且在类组件内没有调用任何钩子


推荐阅读