簡體   English   中英

推送數組在React中返回空

[英]Push array returning empty in React

如果此條件為true,我想在if (totalPagesInSelectedTopic == this.state.topicPageNo + 1) {並將其值分配給狀態的情況下,將值推入topicsVisited數組中。 但是在console.log(this.state.topicsVisited); 其返回的空數組。

import {React, ReactDOM} from '../../../../build/react';

import SelectedTopicPageMarkup from './selected-topic-page-markup.jsx';
import NextPrevBtn from './next-prev-btn.jsx';

export default class SelectedTopicPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      topicPageNo: 0,
      total_selected_topic_pages: 1,
      topicsVisited: []
    };
  };
  navigateBack(topicPageNo) {
    if (this.state.topicPageNo > 0) {
      topicPageNo = this.state.topicPageNo - 1;
    } else {
      topicPageNo = 0;
    }
    this.setState({topicPageNo: topicPageNo});
  };
  navigateNext(totalPagesInSelectedTopic) {
    let topicPageNo;
    if (totalPagesInSelectedTopic > this.state.topicPageNo + 1) {
      topicPageNo = this.state.topicPageNo + 1;
    } else if (totalPagesInSelectedTopic == this.state.topicPageNo + 1) {
      this.props.setTopicClicked(false);

      let topicsVisited = this.state.topicsVisited;
      topicsVisited.push(this.props.topicsID);
      this.setState({topicsVisited: topicsVisited});
    } else {
      topicPageNo = this.state.topicPageNo;
    }
    this.setState({topicPageNo: topicPageNo});
  };
  render() {
    let topicsID = this.props.topicsID;
    let topicPageNo = this.state.topicPageNo;
    console.log(this.state.topicsVisited);
    return (
      <div>
        {this.props.topicPageData.filter(function(topicPage) {
          // if condition is true, item is not filtered out
          return topicPage.topic_no === topicsID;
        }).map(function(topicPage) {
          let totalPagesInSelectedTopic = topicPage.topic_pages.length;
          return (
            <div>
              <div>
                <SelectedTopicPageMarkup headline={topicPage.topic_pages[0].headline} key={topicPage.topic_no}>
                  {topicPage.topic_pages[topicPageNo].description}
                </SelectedTopicPageMarkup>
              </div>
              <div>
                <NextPrevBtn moveNext={this.navigateNext.bind(this, totalPagesInSelectedTopic)} key={topicPage.topic_no} moveBack={this.navigateBack.bind(this, topicPageNo)}/>
              </div>
            </div>
          );
        }.bind(this))}
      </div>
    );
  };
};

我為您創建了一個簡單的范例。

increment(){
    let newCount = this.state.count + 1,
        right = this.state.rightElements,
        left = this.state.leftElements;
    newCount % 2 === 0 ? right.push(newCount) : left.push(newCount)

    this.setState({
      count: newCount,
      rightElements: right,
      leftElements: left,
    });
  }

您可以在此處找到整個示例

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM