首页 > 解决方案 > State React 中没有价值

问题描述

我正在尝试将日期值从输入存储到状态,但状态显示未定义。日期值未存储在状态中。控制台提供未定义 帮助我解决问题

<React 组件有一个内置的状态对象。状态对象是您存储属于组件的属性值的地方。当状态对象改变时,组件会重新渲染。>

import "./admin.css"
import Axios from "axios"
 class Report extends React.Component {
             state={
                append1:[]
                }

date =(e,name)=>{
    if (name === "from") {
        
        let ND = new Date(e.target.value);
  
        ND.setMonth(ND.getMonth());
        var dt = new Date(ND);
        let da = dt.getDate();
        if (da < 10) {
          da = "0" + da;
        }
        let mth = dt.getMonth() + 1;
        if (mth < 10) {
          mth = "0" + mth;
        }
        let yr = dt.getFullYear();
        var ED = yr + "-" + mth + "-" + da;
        console.log(ED)
        
        this.setState({from : ED});
        console.log(this.state.from)
      }
    if (name === "to") {
        
        let ND = new Date(e.target.value);
  
        ND.setMonth(ND.getMonth());
        var dt = new Date(ND);
        let da = dt.getDate();
        if (da < 10) {
          da = "0" + da;
        }
        let mth = dt.getMonth() + 1;
        if (mth < 10) {
          mth = "0" + mth;
        }
        let yr = dt.getFullYear();
        var ED1 = yr + "-" + mth + "-" + da;
     
        this.setState({
            to : ED1
        });
        console.log(this.state.to)
    } 
     
}

onsubmit(){
 console.log(this.state.from)
// console.log(this.state.to)
// let fromto={
//        // from : this.state.from,
//         to: this.state.to
//     }
//     Axios.post("http://localhost:4000/bsdate",fromto).then((response)=>{
//     console.log(response)    
//     this.setState({append1: response.data.data})
//     })
}


render(){
   
    return( 
        <div><center>
            <form>
            Report
            From <input type="date"  onChange={e=>this.date(e,"from")}
            value={this.state.from}/>
            <br/>
             To <input type="date"  onChange={e=>this.date(e,"to")}
              value={this.state.to}
             />   
                <br/> 
           <button type="button" onClick={this.onsubmit}>Submit</button>
           </form>
        {this.state.append1} 
      </center>
        </div>
    )
}
    
} 


export default Report;```

标签: reactjsstate

解决方案


推荐阅读