gpt4 book ai didi

javascript - 在 React 中将类组件转换为功能组件

转载 作者:行者123 更新时间:2023-12-03 15:27:00 25 4
gpt4 key购买 nike

我正在学习 React 钩子(Hook),所以为了做到这一点,我试图将类组件转换为功能组件,但我仍然遇到一些错误。
这是编写为类的原始工作组件:

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;
这是使用钩子(Hook)的转换版本。
 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 is not a function

最佳答案

罪魁祸首似乎是您更新状态的方式,如下所示:

setCounters({ counterss });
这实际上将设置您的 counters状态到具有属性 counterss 的对象,因此您的状态将包含以下内容:
{ counterss: [/* rest of the array */] }
引发的确切错误是指您尝试调用 .filter 的事实。在对象而不是数组上。要解决此问题,您只需像这样更新您的状态:
setCounters(counterss);

关于javascript - 在 React 中将类组件转换为功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66393346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com