Home>

I'm making a todo list with React, and I want to display the date and time of addition.

Source code

This is the source code corresponding to the list.

class TimeLine extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      timeline: props.timeline,
      date: new Date ()
    };
  }
  render () {
    let praise = [];
    for (let i in this.state.timeline) {
      todo.push (
        
          <li>{this.state.timeline [i]}</li>
          <ul>
            {this.state.date.getMonth () + 1}/{this.state.date.getDate ()}-
            {this.state.date.getHours ()}: {this.state.date.getMinutes ()}
          </ul>
        
      );
    }
    return (
      
        <ul>{todo}</ul>
      
    );
  }
}
export default TimeLine;
What you do n’t understand

When this method is implemented and todo is added, the time of the first post is displayed after the second one.
How can I display the date and time of each posting?

  • Answer # 1

    Tuttu56's opinion is like a React code.
    TodoItem is a properly created class, but it is necessary to define it in an appropriate place, create an instance appropriately, and pass it to TimeLine.

    If TimeLine is a class that only displays (= If you add, edit, delete items in the todo list, etc., it is secured by the parent) As pointed out by tutti56, timeline is set in the TimeLine state. There is no need to keep it. If managed in the parent state, when the parent state changes, the parent render will run again, so the TimeLine will be re-rendered

    class TodoItem {
      constructor (title, createdAt) {
        this.title = title;
        this.createdAt = createdAt || new Date ();
      }
    }
    class TimeLine extends React.Component {
      constructor (props) {
        super (props);
        this.state = {};
      }
      render () {
        return (
          
            
              {
                this.props.timeline.map (todoItem =>(
                  

                    

    {todoItem.title}

                    

    {                   `${todoItem.getMonth () + 1}/${todoItem.getDate ()}-${todoItem.getHours ()}: ${todoItem.getMinutes ()}`                 }

                  

                )           )         }                   );   } } export default TimeLine;

  • Answer # 2

    I think usingTimeLinecomponentstate.dateThe
    I guesstimelineis an array withstringoftodo, butdate when addingtimelineHow about having?

    Maybe you need to dosetStateor something, but forget how to use it, modify the following to be usable inreactas appropriate Please give me.

    const timeline = [];
    function addTimeline (text) {
      timeline.push ({
        text,
        date: new Date (),
      });
    }

    And in this case, I don't think it is necessary to putprops.timelinein thestateof theTimeLinecomponent.
    I think it would be better to usemapinstead offor in.