【问题标题】:In React, calling state twice, but second one always one step behind?在 React 中,调用 state 两次,但第二次总是落后一步?
【发布时间】:2021-03-18 16:14:36
【问题描述】:

在 React 中,onButtonClick 方法会正确更新 currentIndex 上的状态,但不会更新 currentText 上的状态。如果您查看两个控制台日志,您会看到 currentText 落后于一个。如何在同一个 setState 调用中修复它?是否与 React 异步有关?

// dependencies
import React from 'react';
// local files
import './App.css';

const sections = [
  {
    title: 'Section 1',
    content: 'Lorem ipsum dolor sit amet consectetur adipisicing elit.',
  },
  {
    title: 'Section 2',
    content: 'Cupiditate tenetur aliquam necessitatibus id distinctio quas nihil ipsam nisi modi!',
  },
  {
    title: 'Section 3',
    content: 'Animi amet cumque sint cupiditate officia ab voluptatibus libero optio et?',
  },
]

class App extends React.Component {
  // state
  state = {
    currentIndex: 0,
    currentText: ''
  };

  // event handlers
  onButtonClick(index) {
    this.setState({
      currentIndex: index,
      currentText: this.state.currentIndex
    }, function() {
      console.log(this.state.currentIndex);
      console.log(this.state.currentText);
    });
  }

  // helpers
  renderButtons() {
    return sections.map((item, index) => (
      <li key={item.title}>
        <button onClick={() => this.onButtonClick(index)}>{item.title}</button>
      </li>
    ));
  }

  renderContent() {
    return this.state.currentText;
  }

  render() {
    return (
      <div className="App">
        <ul>
          {this.renderButtons()}
        </ul>
        <p>{this.renderContent()}</p>
      </div>
    );
  };
}
export default App;

【问题讨论】:

  • this.state.currentIndex 不会立即更新,因此您仍将拥有旧值。您是否还打算将currentText 设置为int
  • 根据“单一事实来源”的原则,您甚至不应该将currentText 存储到状态。您应该始终从 state.currentIndex 动态计算它。

标签: reactjs


【解决方案1】:

改为这样做:

  onButtonClick(index) {
    this.setState({
      currentIndex: index,
      currentText: index
    }, function() {
      console.log(this.state.currentIndex);
      console.log(this.state.currentText);
    });
  }

【讨论】:

    【解决方案2】:

    这可能会有所帮助

    onButtonClick(index) {
        this.setState({
          ....
          currentText: sections[index].title, // update text also when selected
        }, function() {
          .....
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      相关资源
      最近更新 更多