2 回答
TA贡献1866条经验 获得超5个赞
这是因为您将两个反应组件范例组合在一起。我们没有函数,您需要以这种方式更改代码才能使用:renderFunctional ComponentClass Component
class App extends React.Component {
state = {
counters: [
{
id: 1,
value: 4
},
{
id: 2,
value: 0
},
{
id: 3,
value: 0
},
{
id: 4,
value: 0
}
]
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = {
...counter
};
counters[index].value++;
console.log(this.state.counters[index]);
this.setState({
counters
});
};
handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({
counters
});
};
handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({
counters
});
};
render() {
return (
<div>
<React.Fragment>
<Navbar />
<main className="container">
<Counters
counters={this.state.counters}
onReset={this.handleReset}
onIncrement={this.handleIncrement}
onDelete={this.handleDelete}
/>
</main>
</React.Fragment>
</div>
);
}
}
或以这种方式使用Functional Component
function App() {
const [state, setState] = React.useState({
counters: [
{
id: 1,
value: 4
},
{
id: 2,
value: 0
},
{
id: 3,
value: 0
},
{
id: 4,
value: 0
}
]
});
const handleIncrement = counter => {
const counters = [...state.counters];
const index = counters.indexOf(counter);
counters[index] = {
...counter
};
counters[index].value++;
console.log(state.counters[index]);
setState({
counters
});
};
const handleReset = () => {
const counters = state.counters.map(c => {
c.value = 0;
return c;
});
setState({
counters
});
};
const handleDelete = counterId => {
const counters = state.counters.filter(c => c.id !== counterId);
setState({
counters
});
};
return (
<div>
<React.Fragment>
<Navbar />
<main className="container">
<Counters
counters={state.counters}
onReset={handleReset}
onIncrement={handleIncrement}
onDelete={handleDelete}
/>
</main>
</React.Fragment>
</div>
);
}
TA贡献1851条经验 获得超5个赞
函数组件中有一个方法。您已经将基于类的组件与基于函数的组件混合在一起。只需返回所需的值,删除呈现方法(将代码放在其中,外部),并将其余函数转换为常量:render()
function App() {
state = {
counters: [
{
id: 1,
value: 4
},
{
id: 2,
value: 0
},
{
id: 3,
value: 0
},
{
id: 4,
value: 0
}
]
};
const handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = {
...counter
};
counters[index].value++;
console.log(this.state.counters[index]);
this.setState({
counters
});
};
const handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState({
counters
});
};
const handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({
counters
});
};
return (
<div>
<React.Fragment>
<Navbar />
<main className="container">
<Counters
counters={this.state.counters}
onReset={this.handleReset}
onIncrement={this.handleIncrement}
onDelete={this.handleDelete}
/>
</main>
</React.Fragment>
</div>
);
}
添加回答
举报
