反应状态值不更新

时间:2016-02-15 12:10:12

标签: javascript reactjs

我想通过传递名为topicsVisited的变量中的值来更新topicsVisited状态的值。但是,它没有更新值。当用户访问主题页面的末尾时,它应该将topicID值推送到数组,该数组值将存储在localstorage中并转移到该状态。

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) {
      let topicsVisited = JSON.parse(localStorage.getItem('topicsVisited')) || [];
      topicsVisited.push(parseInt(this.props.topicsID));
      localStorage.setItem("topicsVisited", JSON.stringify(topicsVisited));
      this.setState({topicsVisited: topicsVisited});
      console.log(this.state.topicsVisited);
      this.props.setTopicClicked(false);
    } else {
      topicPageNo = this.state.topicPageNo;
    }
    this.setState({topicPageNo: topicPageNo});
  };

  render() {
    let topicsID = this.props.topicsID;
    let topicPageNo = this.state.topicPageNo;
    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>
    );
  };
};

2 个答案:

答案 0 :(得分:2)

setState文档谈论两件重要的事情:

  

无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以获得性能提升。

  

第二个(可选)参数是一个回调函数,它将在setState完成并重新呈现组件后执行。

您可能希望合并两个setState来电或使用回调来完成状态更改后您想要完成的工作。

回调看起来像:

this.setState({topicsVisited: topicsVisited}, function() {
    console.log(this.state.topicsVisited);
    this.props.setTopicClicked(false);
}.bind(this));

答案 1 :(得分:0)

这个setState方法/函数不是正确的代码,而不是直接尝试更改状态变量吗?

 {
"fields": ["comments.name", "title", "body", "tags"],
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "comments", 
            "query": {
              "bool": {
                "must": [ 
                  { "match": { "comments.name": "john" }},
                  { "match": { "comments.age":  28     }}
                ]
        }}}}
      ]
}}}



{"took":5,"timed_out":false,"_shards":
{"total":1,"successful":1,"failed":0},"hits":
{"total":1,"max_score":2.4114075,"hits":
[{"_index":"test","_type":"produkt","_id":"1","_score":2.4114075,"fields":
{"comments.name":["Mary Brown","John Smith"],"title":["Investment 
secrets"],"body":["What they don't tell you ..."],"tags":
["shares","equities"]}}]}}