reactjs - 如何正确缓解 reactjs 中的无效钩子问题
问题描述
我正在尝试使用reactjs从airtable.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;
解决方案
useBase
并且useRecords
不能在类组件中调用钩子,但是您可以采取一些解决方法来避免通过将传递base
并records
作为道具的导出箭头函数重写代码
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
并且在类组件内没有调用任何钩子
推荐阅读
- servicestack - ServiceStack AutoQuery 合成字段
- javascript - React.JS 使用组件
- apache-spark - pyspark:StopWordsRemover 参数语言环境给定的值无效
- webview - Flutter:webview_flutter 在同一个 webview 小部件中更新 url
- mysql - 在从视图中选择时更改数据类型
- reactjs - 未处理的拒绝(TypeError):this.state.products.map 不是函数
- php - 使用php将图像和视频文件插入数据库
- ruby-on-rails - 在 Rails 5 中批量分配属性和保存记录
- c++ - 从第一原则反转字符串 - 有什么问题?
- linq - 在不更改组顺序的情况下订购展平列表