Options -Indexes
每当我单击按钮以def convert_12_to_24(s12)
hr = s12[0,2].to_i
hr = if s12[-2,2] == 'AM'
hr == 12 ? 0 : hr
else
hr == 12 ? 12 : hr + 12
end
"%02d%s" % [hr, s12[2..-3]]
end
convert_12_to_24 "12:00:00AM" #=> "00:00:00"
convert_12_to_24 "12:59:59AM" #=> "00:59:59"
convert_12_to_24 "01:00:00AM" #=> "01:00:00"
convert_12_to_24 "11:59:00AM" #=> "11:59:00"
convert_12_to_24 "12:00:00PM" #=> "12:00:00"
convert_12_to_24 "12:59:59PM" #=> "12:59:59"
convert_12_to_24 "01:00:00PM" #=> "13:00:00"
convert_12_to_24 "11:59:59PM" #=> "23:59:59"
值时,我都想同步"%02d%s"
。因此流程是先class Mycomponent extends Component {
state = {
text: null
}
componentDidMount() {
fetch("http://localhost:3000/books/4")
.then(response => response.json())
.then(data => this.setState({ text: data.title // this data.value is "Learn Javascript" }));
}
fetchPUT(val) {
fetch("http://localhost:3000/books/4", {
method: "PUT",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({ value: val })
}).then(e => console.log(e));
}
onMouseDown = e => {
this.setState({
text: this.refs.myinput.value,
});
this.fetchPUT(this.refs.myinput.value);
};
render() {
const { text } = this.state;
return (
<div>
<input
type="text"
value={text}
onMouseLeave={this.onMouseLeave}
ref="myinput"
/>
</div>
)
}
}
然后更改值,在this.text
之后单击按钮PUT
,然后再次获取
答案 0 :(得分:2)
您不必从后端获取数据即可将值与当前文本同步。而是将setState
中的onMouseDown
回调用作:
onMouseDown = e => {
this.setState({
text: this.refs.myinput.value,
}, () => {
this.fetchPUT(this.refs.myinput.value);
});
};
这里,将在进行放置调用之前设置状态,并且由于您拥有更新的值,因此不必获取值。卸载该组件并再次安装后,它将从您的componentDidMount
中获取更新的值。
了解更多here
也
在渲染功能中,使用onChange
而不是onMouseDown
(甚至不使用),因为这样可以减少混乱。使用debounce,这样您就不必在每次更改时都进行许多API调用。
onChange = _.debounce((event) => {
const text = event.target.value;
this.setState({text}, () => {
this.fetchPUT(text);
})
}, 500)
render() {
const { text } = this.state;
return (
<div>
<input
type="text"
value={text}
onChange={this.onChange}
/>
</div>
)
}