[英]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.