简体   繁体   English

在React补丁后更新状态

[英]Updating State after Patch in React

I am trying to figure out how to automatically update the state after a patch request so when one clicks the button, it will automatically add their like within the counter. 我试图弄清楚如何在补丁请求后自动更新状态,因此当单击按钮时,它将在计数器内自动添加它们的样式。 Unfortunately, it still takes a page load to update. 不幸的是,它仍然需要页面加载来更新。 Is there anything you may be seeing on this? 您可能对此有什么看法? Any help greatly appreciated thank you. 任何帮助,不胜感激,谢谢。

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;

Welcome to SO 欢迎来到SO

I don't see your props declared anywhere but I assume it is for space saving and readability purposes. 我看不到任何地方声明您的道具,但我想这是为了节省空间和可读性。

Have you tried using React Component's built-in lifecycle method componentDidUpdate(prevProps) ? 您是否尝试过使用React Component的内置生命周期方法componentDidUpdate(prevProps)

In your case you would do 在你的情况下,你会做

componentDidUpdate(prevProps) {
  // you always need to check if the props are different
  if (this.props.counter !== prevProps.counter) {
    this.setState({ counter: this.props.counter });
  }
}

You can find the documentation here: https://reactjs.org/docs/react-component.html#componentdidupdate 您可以在此处找到文档: https : //reactjs.org/docs/react-component.html#componentdidupdate

That being said, I do not see why you wouldn't display the prop directly instead of duplicating it in a state... As in: 话虽这么说,我不明白为什么您不直接显示道具而不是在状态下复制道具...如:

render() {
  return (
    <div className="customContainer">
      <button onClick={this.handleSubmit}>{this.props.counter}</button>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM