如果此条件为真topicsVisited
,我想在if (totalPagesInSelectedTopic == this.state.topicPageNo + 1) {
数组中推送值并将其值赋值给状态。但是在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>
);
};
};
答案 0 :(得分:1)
我为你创造了一个简单的例子。
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,
});
}
您可以找到完整的工作示例 here
感谢。