我是 React 的新手。我的問題在 React 開發(fā)人員中可能很常見,并且有很多相同的問題,但我仍然不知道如何解決。我仍然必須單擊兩次才能更新 UI 狀態(tài)。第一次點擊只調(diào)用事件處理程序,但不更新狀態(tài)中的計數(shù)器變量。即使我像下面這樣使用 setState() 的回調(diào)形式:this.setState({ hasButtonBeenClicked: true }, () => {console.log("Clicked")});第一次點擊也沒有達到 console.log("Clicked") !應(yīng)用程序.jsimport 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> ) }}
React setState() 需要點擊 2 次來更新 UI
藍山帝景
2023-05-11 14:45:51