我正在尝试弄清楚如何在补丁请求后自动更新状态,以便当单击按钮时,它会自动在计数器中添加它们的喜欢。不幸的是,仍然需要加载页面才能更新。您对此有什么看法吗?任何帮助都非常感谢,谢谢。
import React, { Component } from "react";
import "./Like.css";
class Button extends Component {
constructor(props) {
super(props);
this.state = {
counter: this.props.counter
};
}
handleSubmit = event => {
event.preventDefault();
fetch(`http://localhost:3001/api/tracklists/${this.props.id}`, {
method: "PATCH",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
tracklist: {
title: this.props.title,
url: this.props.url,
genre: this.props.genre,
tracklist: this.props.tracklist,
likes: this.props.counter + 1
}
})
})
.then(response => response.json())
.then(response => {
this.setState({
counter: this.props.counter
});
});
};
render() {
return (
<div className="customContainer">
<button onClick={this.handleSubmit}>{this.state.counter}</button>
</div>
);
}
}
export default Button;
最佳答案
欢迎来到SO
我没有在任何地方看到你的 props 声明,但我认为这是出于节省空间和可读性的目的。
您是否尝试过使用 React Component 的内置生命周期方法 componentDidUpdate(prevProps)
?
在你的情况下你会这样做
componentDidUpdate(prevProps) {
// you always need to check if the props are different
if (this.props.counter !== prevProps.counter) {
this.setState({ counter: this.props.counter });
}
}
您可以在此处找到文档:https://reactjs.org/docs/react-component.html#componentdidupdate
话虽这么说,我不明白为什么你不直接显示 Prop 而不是在状态中复制它......如:
render() {
return (
<div className="customContainer">
<button onClick={this.handleSubmit}>{this.props.counter}</button>
</div>
);
}
关于javascript - React 中打补丁后更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52969889/