2 回答

TA貢獻1866條經(jīng)驗 獲得超5個贊
這是因為您將兩個反應(yīng)組件范例組合在一起。我們沒有函數(shù),您需要以這種方式更改代碼才能使用: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條經(jīng)驗 獲得超5個贊
函數(shù)組件中有一個方法。您已經(jīng)將基于類的組件與基于函數(shù)的組件混合在一起。只需返回所需的值,刪除呈現(xiàn)方法(將代碼放在其中,外部),并將其余函數(shù)轉(zhuǎn)換為常量: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>
);
}
添加回答
舉報