javascript - React 中打补丁后更新状态

标签 javascript reactjs fetch

我正在尝试弄清楚如何在补丁请求后自动更新状态,以便当单击按钮时,它会自动在计数器中添加它们的喜欢。不幸的是,仍然需要加载页面才能更新。您对此有什么看法吗?任何帮助都非常感谢,谢谢。

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/

相关文章:

javascript - 使用 Javascript 确定 JSF 库资源

javascript - 如何重新加载 jquery 以便它适用于下一个进程

javascript - 当我的组件渲染时收到警告 "Warning: Each child in a list should have a unique "key"prop."

javascript - 通过 React 延迟导入和 Webpack 不会发生代码分割

javascript - Map 在 React 中未定义

javascript - 加载 Google 电子表格以使用传单进行可视化

javascript - 如何从地址栏中删除网络摄像头图标

reactjs - 如何在不更新存储的情况下将成功状态传递回组件

javascript - 使用 fetch javascript 查询字符串

node.js - 由于 CORS,无法在 Express 和 React 应用程序之间进行获取