如何在反应中的方法之间进行通信?
问题描述:
我目前有两种方法,SelectedTopicPage
组件即navigateNext
和render
。我想从navigateNext
方法将topicPageNo
的值传递给render
方法。在React中推荐的方法是什么?当我试图声明:如何在反应中的方法之间进行通信?
topicPageNo = navigateNext.state.topicPageNo;
它给undefined error
。
var SelectedTopicPage = React.createClass({
navigateNext: function() {
let topicPageNo = '2';
this.setState({topicPageNo : topicPageNo});
},
render: function() {
let topicsID = this.props.topicsID;
let navigateNext = this.navigateNext;
let topicPageNo = navigateNext.state.topicPageNo;
return (
<div>
{this.props.topicPages.filter(function(topicPage) {
return topicPage.topic_no === topicsID && topicPage.topic_page_no === topicPageNo; // if condition is true, item is not filtered out
}).map(function (topicPage) {
return (
<div>
<div>
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
</div>
<div>
<NextPrevBtn moveNext={navigateNext}/>
</div>
</div>
);
})}
</div>
);
}
});
答
你必须使用this
所以你的代码应该是let topicPageNo = this.state.topicPageNo;
和您的组件应该有一个像
getInitialState:function()
{
return{
topicPageNo:0
}
}
的方法更新其在控制台给这个错误后'遗漏的类型错误:无法读取属性'topicPageNo'为null –