javascript - 在 react.js 中填充必要的数据
问题描述
class TodoApp extends React.Component {
constructor(){
super();
this.state = {
}
}
componentWillMount(){
this.getSampleData();
}
getSampleData(){
console.log('enter value');
this.setState({
sampleData:{
labels: ['Jan', 'Feb', 'Mar', 'Apr',
'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [
{
label: '2017',
data: [92, 50, 33, 70, 122, 22, 21,20, 22, 215, 278, 190],
},
{
label: '2018',
data: [22, 210, 520, 278, 260, 245, 221,516, 718, 174, 154, 148],
},
]
}} );
/// Here i want to get monthdata that to be taken from sampleData
monthData:
//for example this month 221 should come here,from the sampleData
console.log('end value');
}
render() {
return (
<div>
<h2>Todos:</h2>
<p> monthData</p>
</div>
)
}
}
我是 React.js 的新手。但是在标签中显示时我无法放置特定月份的数据。虽然我在这里提到了monthData这个词,但我对变量引用(sampleData)和从html中获取数据没有适当的了解。在不使用 monthData 变量的情况下,直接从 sampleData 在 p 标签中制作特定月份值对我来说也很好。谁可以帮我这个事。谢谢。
解决方案
在这里,我得到了基于当前月份的数据。同样,如果您想要动态的,您可以将其更改为年份。请检查下面的更新片段:
class TodoApp extends React.Component {
constructor(){
super();
this.state = {
}
}
componentWillMount(){
this.getSampleData();
}
getSampleData(){
console.log('enter value');
this.setState({
sampleData:{
labels: ['Jan', 'Feb', 'Mar', 'Apr',
'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [
{
label: '2017',
data: [92, 50, 33, 70, 122, 22, 21,20, 22, 215, 278, 190],
},
{
label: '2018',
data: [22, 210, 520, 278, 260, 245, 221,516, 718, 174, 154, 148],
},
]
}} );
/// Here i want to get monthdata that to be taken from sampleData
monthData:
//for example this month 221 should come here,from the sampleData
console.log('end value');
}
render() {
const d = new Date();
const m = d.getMonth();
const monthData = this.state.sampleData.datasets[1].data[m];
return (
<div>
<h2>Todos:</h2>
<p>Current Month data : {monthData}</p>
</div>
)
}
}
这里data[m]代表当前月份(6 - 七月)。
推荐阅读
- ios - 在弹出键盘时实现向上移动视图时修复这些丑陋的结果
- html - 如何将文本转换为 Angular 4 中的 HTML 文本
- python - 根据 np.where 或类似的字典值到数组
- uwp - UWP 应用程序 MainWindow 未在左侧显示第二个按钮
- regex - 如何使用正则表达式返回一行但不包括表达式?
- design-patterns - 基于消息类型处理不同消息的设计模式
- jquery - 如何使用位置:绝对并具有自动高度
- php - 如何在laravel中循环一个数据
- javascript - 在 Illustrator 中创建一行框
- python - 从 IMF api 作为 JSON 检索数据是 Pandas DataFrame 中字典的嵌套列表需要 time_period 和 obs_value