为什么仅在onChange之后才呈现内容?

时间:2019-04-15 18:51:46

标签: javascript arrays reactjs rc-slider

我正在使用rc-slider从数组中获取一堆值并将其呈现在我的组件中。

const array = ["Hey", "Ho", "Me", "Too", "See"]
class App extends Component {
  state = { sliderValues: [0, 1, 2, 3, 4] };

  handleChange = sliderValues => {
    this.setState({ sliderValues }, () => console.log(array[this.state.sliderValues]));
  };

  render() {
    const renderContent = array.map((value, index) => {
      console.log(value, 'value')
      console.log(index, 'index')
      if (index === this.state.sliderValues) {
        return (
          <div>
            <h1>{value}</h1>
          </div>
        )
      }
    })
    return (
      <div>
        {renderContent}
        <Slider onChange={this.handleChange} min={0} max={4} defaultValue={this.state.sliderValues} marks={{ 0: 250, 1: 500, 2: 750, 3: 1000, 4: 1500 }} step={null} />
      </div>
    )
  }
}

我只想一次显示数组中的一项。除了在初始渲染上,一切都正常工作。您会注意到,组件仅在与<Slider />.进行交互后才呈现。

这是为什么?

Codesandbox

1 个答案:

答案 0 :(得分:1)

    import React, {Component} from "react";
    import ReactDOM from "react-dom";
    import Slider from 'rc-slider'
    import "./styles.css";

    const array = ["Hey", "Ho", "Me", "Too", "See"]
    class App extends Component {
      // you need to provide an initial value to be rendered at the first time
      state = { sliderValues: 0 };

      handleChange = sliderValues => {
        this.setState({ sliderValues }, () => console.log(array[this.state.sliderValues]));
      };

      render() {
        const renderContent = array.map((value, index) => {
          console.log(value, 'value')
          console.log(index, 'index')
          if (index === this.state.sliderValues) {
            return (
              <div key={value}>
                <h1>{value}</h1>
              </div>
            )
          }
        })
        return (
          <div>
            {renderContent}
            <Slider onChange={this.handleChange} min={0} max={4} defaultValue={this.state.sliderValues} marks={{ 0: 250, 1: 500, 2: 750, 3: 1000, 4: 1500 }} step={null} />
          </div>
        )
      }
    }

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);