寻找将时间戳输出到组件的React Button onClick事件

时间:2019-03-15 01:01:17

标签: javascript html node.js reactjs

我仍在学习Javascript和React的世界-请原谅我缺乏知识:)

我正在尝试基本上过滤每天的点击次数,即使用时间戳。我最初的思维过程是这样的:

  • onClick函数中,将time设置为moment().toDate()
  • 在单独的stats.js文件中将this.state.time输出到React组件

console.log(moment().toDate())确实会在按下按钮时输出时间戳,这很好,但是我无法渲染它。

有什么想法吗?

到目前为止,我的App.js文件是

import Layout from '../components/MyLayout.js'
import Header from '../components/Header.js'
import Link from 'next/link'
import React, { Component } from "react";
import { spring } from 'popmotion';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const moment = require('moment');
import LinearProgress from '@material-ui/core/LinearProgress';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      response: undefined
    };
    this.incrementCounter = this.incrementCounter.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    this.setState({
      count: parseInt(localStorage.getItem("count")) || 0
    });
  }

  incrementCounter() {
    const count = this.state.count + 1;
    localStorage.setItem("count", count);
    this.setState({
      count: count
    });
  }

  handleSubmit = (event) => {
    event.preventDefault();
    fetch('/', { method: 'POST' })
    .then(response => response.text())
    .then(textValue => this.setState({ response: textValue }))
    .then(time => this.setState({ time: moment().toDate() }))
    .then(console.log(moment().toDate()));
  }

  render() {
    return (
        <main>
            <Header />
              <div style={{paddingTop: "150px"}}>
                <Typography variant="title" color="inherit">
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <h1 style={{ fontFamily:"Arial", fontSize:"50px" }}>Magic 8 Ball</h1>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <form className="question-input" onSubmit={this.handleSubmit}>
                      <TextField
                        id="inputquestion"
                        autoComplete="off"
                        placeholder="Ask your question..."
                        margin="normal"
                        style={{ width:"200px", paddingRight:"10px" }}
                      />
                      <Button
                        variant="contained"
                        type="submit"
                        color="primary"
                        onClick={ this.incrementCounter.bind(this) }
                        id="submitquestion"
                        style={{ width: "100px", fontSize:17 }}>Shake Me!
                      </Button>
                    </form>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <p>Magic 8 Ball says...</p>
                  </div>
                  <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                    <p>{this.state.response}</p>
                  </div>
                </Typography>
              </div>
        </main>
    )
  }
}

export default App;

我的stats.js文件(最终要在其中输出统计信息):

import Header from '../components/Header.js'
import Link from 'next/link'
import { Component } from "react";
const moment = require('moment');
import { Chart } from "react-charts";
import Typography from '@material-ui/core/Typography';

class StatsPage extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      time: undefined
    };
    this.incrementCounter = this.incrementCounter.bind(this);
  }

  componentDidMount() {
    this.setState({
      count: parseInt(localStorage.getItem("count")) || 0
    });
  }

  incrementCounter() {
    const count = this.state.count + 1;
    localStorage.setItem("count", count);
    this.setState({
      count: count
    });
  }

  render() {
    return (
      <main>
        <Header />
          <h1>Game Statistics</h1>
            <Typography variant="title" color="inherit">
                <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                  <p>Total questions: {this.state.count}</p>
                </div>
                <div style={{display: 'flex',  justifyContent:'center', alignItems:'center'}}>
                  <p>Last question timestamp: {this.state.time}</p>
                </div>
              </Typography>
              <style jsx>{`
                h1 {
                  font-family:"Arial";
                  font-size:50px;
                }`}
              </style>
      </main>
    )
  }
}

export default StatsPage;

1 个答案:

答案 0 :(得分:0)

您正在应用程序中设置状态,但随后再也不会使用它。您在StatsPage中使用状态,但从未设置。每个组件都有其自己的状态,因此请仅选择一个您要对此负责的组件并在那里进行处理。如果不确定要使用哪个组件,请在组件树中找到需要与时间交互(设置或使用时间)的最高组件,然后将状态放在那里。然后,它可以将它作为道具传递给所有关心它的孩子。