在 React 中将类组件转换为功能组件
Posted
技术标签:
【中文标题】在 React 中将类组件转换为功能组件【英文标题】:Convert class component to functional component in React 【发布时间】:2021-05-29 06:41:12 【问题描述】:我正在学习 React 钩子,所以为了做到这一点,我尝试将类组件转换为功能组件,但仍然遇到一些错误。
这是写成类的原始工作组件:
import React, Component from 'react';
import NavBar from './components/navbar';
import Counters from './components/counters';
class App extends Component
state =
counters: [
id: 0, value: 5 ,
id: 1, value: 1 ,
id: 2, value: 2 ,
],
;
handleDelete = (counterId) =>
const counters = this.state.counters.filter((c) => c.id !== counterId);
this.setState( counters );
;
handleReset = () =>
const counters = this.state.counters.map((c) =>
c.value = 0;
return c;
);
this.setState( counters );
;
handleIncrement = (counter) =>
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = ...counter ;
counters[index].value++;
this.setState( counters );
;
render()
return (
<React.Fragment>
<NavBar
totalCounters=this.state.counters.filter((c) => c.value > 0).length
/>
<main className='container'>
<Counters
counters=this.state.counters
onReset=this.handleReset
onDelete=this.handleDelete
onIncrement=this.handleIncrement
/>
</main>
</React.Fragment>
);
export default App;
这是使用钩子的转换版本。
import React, useState from 'react';
import NavBar from './components/navbar';
import Counters from './components/counters';
const App = () =>
const [counters, setCounters] = useState([
id: 0, value: 5 ,
id: 1, value: 1 ,
id: 2, value: 2 ,
]);
const handleDelete = (counterId) =>
const counterss = counters.filter((c) => c.id !== counterId);
setCounters( counterss );
;
const handleReset = () =>
const counterss = counters.map((c) =>
c.value = 0;
return c;
);
setCounters( counterss );
;
const handleIncrement = (counter) =>
const counterss = [...counters];
const index = counterss.indexOf(counter);
counterss[index] = ...counter ;
counterss[index].value++;
setCounters( counterss );
;
return (
<React.Fragment>
<NavBar totalCounters=counters.filter((c) => c.value > 0).length />
<main className='container'>
<Counters
counters=counters
onReset=handleReset
onDelete=handleDelete
onIncrement=handleIncrement
/>
</main>
</React.Fragment>
);
;
export default App;
大部分都可以正常工作,但它一直抛出一个错误,说过滤器不是一个函数。这是消息:
TypeError: counters.filter 不是函数
【问题讨论】:
【参考方案1】:罪魁祸首似乎是您更新状态的方式,如下所示:
setCounters( counterss );
这实际上会将您的counters
状态设置为具有counterss
属性的对象,因此您的状态将包含以下内容:
counterss: [/* rest of the array */]
引发的确切错误是指您试图在对象而不是数组上调用.filter
。要解决此问题,您只需像这样更新您的状态:
setCounters(counterss);
【讨论】:
【参考方案2】:它会引发错误,因为您将新状态设置为对象setCounters( counterss );
。但是你想要一个数组:setCounters(counterss);
。这样在第二次调用setCounters
时就不会抛出错误。
【讨论】:
【参考方案3】:setCounters( counterss )
应该是
setCounters(counterss)
【讨论】:
以上是关于在 React 中将类组件转换为功能组件的主要内容,如果未能解决你的问题,请参考以下文章