我有这样一个函数,从两周前设置日期:
dateTwoWeeksAgo: function(){
var twoWeeksAgo = new Date().toDateString();
this.setState({twoWeeksAgo: twoWeeksAgo});
},
我有调用这个函数的代码。但这并没有奏效。我如何显示一个变量,我正在设置的状态或从一个函数返回?
<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo} : {this.state.commits.length} </h2>
选项1:为了显示twoWeeksAgo
的值,您可以:
<h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>
更新状态的实际方法- dateTwoWeeksAgo()
-可以在componendDidMount
生命周期方法中调用。
https://facebook.github.io/react/docs/component-specs.html mounting-componentdidmount
下面是一个演示:http://codepen.io/PiotrBerebecki/pen/LRAmBr
选项2:或者,您可以像这样调用返回所需日期的方法(http://codepen.io/PiotrBerebecki/pen/NRzzaX),
const App = React.createClass({
getInitialState: function() {
return {
commits: ['One', 'Two']
};
},
dateTwoWeeksAgo: function() {
return new Date().toDateString();
},
render: function() {
return (
<div>
<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo()} : {this.state.commits.length} </h2>
</div>
);
}
})
代码选项1:
const App = React.createClass({
getInitialState: function() {
return {
twoWeeksAgo: null,
commits: ['One', 'Two']
};
},
componentDidMount: function() {
this.dateTwoWeeksAgo();
},
dateTwoWeeksAgo: function() {
var twoWeeksAgo = new Date().toDateString();
this.setState({twoWeeksAgo: twoWeeksAgo});
},
render: function() {
return (
<div>
<h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>
</div>
);
}
})
ReactDOM.render(
<App />,
document.getElementById('app')
);
应该是:
<h2 className="headings" id="commitTotal"> Commits since {this.state.dateTwoWeeksAgo} : {this.state.commits.length} </h2>
差异为this.state.dateTwoWeeksAgo
对于您的代码示例,我建议采用这种方法
dateTwoWeeksAgo: function(){
return new Date().toDateString();
},
<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo()} : {this.state.commits.length} </h2>
如果你真的想使用状态,你需要改变{this.dateTwoWeeksAgo} to {this.state.dateTwoWeeksAgo}