我是 React 的新手。我的问题在 React 开发人员中可能很常见,并且有很多相同的问题,但我仍然不知道如何解决。我仍然必须单击两次才能更新 UI 状态。第一次点击只调用事件处理程序,但不更新状态中的计数器变量。即使我像下面这样使用 setState() 的回调形式:
this.setState({ hasButtonBeenClicked: true }, () => {console.log("Clicked")});
第一次点击也没有达到 console.log("Clicked") !
应用程序.js
import React, { Component, useState } from "react";
import { Summary } from "./Summary";
import ReactDOM from "react-dom";
let names = ["Bob", "Alice", "Dora"]
function reverseNames() {
names.reverse();
ReactDOM.render(<App />, document.getElementById('root'));
}
function promoteName(name) {
names = [name, ...names.filter(val => val !== name)];
ReactDOM.render(<App />, document.getElementById('root'));
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
incrementCounter = (increment) => this.setState({counter: this.state.counter + increment});
render() {
return (
<table className="table table-sm table-striped">
<thead>
<tr><th>#</th><th>Name</th><th>Letters</th></tr>
</thead>
<tbody>
{names.map((name, index) =>
<tr key={name}>
<Summary index={index} name={name}
reverseCallback={() => reverseNames()}
promoteCallback={() => promoteName(name)}
counter={this.state.counter}
incrementCallback={this.incrementCounter}
/>
</tr>
)}
</tbody>
</table>
)
}
}
MM们
相关分类