[英]React : state object property is not updating
我正在嘗試更新我的狀態,但與此同時,當我在控制台中控制更新的狀態值時,它會給我一條消息,表明您的狀態值是undefined
。 有人可以幫助我如何解決這個問題。 我正在使用rc-time-picker
picker 選擇時間並將所選時間存儲在 localstorage 中,但它沒有更新狀態值謝謝
代碼
import 'rc-time-picker/assets/index.css';
import React, { Component } from 'react';
import TimePicker from 'rc-time-picker';
import moment from 'moment';
const format = 'h:mm a';
const now = moment().hour(0).minute(0);
class Time extends Component {
constructor(){
super();
this.state={
value : ''
}
}
newHandleChange=(value)=>{
this.setState({
value: localStorage.setItem("currentTime",value.format('h:mm a'))
})
}
render(){
console.log("state data",this.state.value)
return(
<div>
<TimePicker
showSecond={false}
defaultValue={now}
className="xxx"
onChange={this.newHandleChange}
format={format}
use12Hours
inputReadOnly
fieldName="time"
/>
</div>
)
}
}
export default Time;
您獲得undefined
的原因是因為您正在使用從調用localStorage.setItem
返回的值設置新狀態,該值是undefined
。
以下是您需要做的事情:
class Time extends Component {
constructor(props) {
super(props)
this.state = { value: '' }
}
// ...
newHandleChange = (value) => {
const time = value.format('h:mm a')
localStorage.setItem('currentTime', time)
this.setState({
value: time
})
}
}
這樣,您將新時間保存到一個變量中,並使用它來更新localStorage
currentValue
和組件中的state
。
在constructor
初始化state
,您應該將props
傳遞給super
:
constructor(props){
super(props);
this.state={
value : ''
}
}
你得到的undefined
只是getItem()
的結果
您需要為狀態設置正確的值,請檢查以下代碼
newHandleChange=(value)=>{
localStorage.setItem("currentTime",value.format('h:mm a')) // if you really needs the local storage.
this.setState({
value: value.format('h:mm a')
})
}
嘗試使用這個`
newHandleChange =val=> {
const value=localStorage.setItem('currentTime', val.format('h:mm a'))
this.setState({
value
})
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.