[英]reactjs fetch PUT value and pass value to state
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
值。 所以流程是先fetch
然后更改值,在PUT
之后单击按钮PUT
值,然后再次获取
您无需从后端获取数据即可将值与当前文本同步。 而是在onMouseDown
使用setState
回调为:
onMouseDown = e => {
this.setState({
text: this.refs.myinput.value,
}, () => {
this.fetchPUT(this.refs.myinput.value);
});
};
在这里,状态将在进行放置调用之前设置,并且由于您拥有更新的值,因此无需获取值。 卸载组件并再次安装时,它将从componentDidMount
获取更新的值。
在这里阅读更多
也
在渲染函数中,使用onChange
而不是onMouseDown
(甚至不使用),因为这样可以减少混乱。 使用反跳,这样您就不必在每次更改时都进行许多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>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.