В React состояние вызывается дважды, но второе всегда на шаг позади?

#reactjs

#reactjs

Вопрос:

В 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;
 

Комментарии:

1. this.state.currentIndex не будет обновляться немедленно, поэтому у вас все еще будет старое значение. Также вы имеете в виду установить значение currentText an int ?

2. По принципу «единого источника истины» вы даже не должны сохранять currentText состояние. Вы всегда должны вычислять его динамически state.currentIndex .

Ответ №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() {
      .....
    });
  }