【问题标题】:Need help refreshing a component in React.js without reloading the window/page需要帮助刷新 React.js 中的组件而不重新加载窗口/页面
【发布时间】:2020-12-17 14:41:13
【问题描述】:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { Button } from "react-bootstrap";
import { FiRefreshCw } from "react-icons/fi";

const Todo = (props) => (
  <tr>
    <td>{props.todo.todo_description}</td>
    <td>{props.todo.todo_responsible}</td>
    <td>{props.todo.todo_priority}</td>
    <td>
      <Link to={"/edit/" + props.todo._id}>
        <Button size="sm" variant="info">
          Update
        </Button>
      </Link>
      &#8195;
      <Link to={"/delete/" + props.todo._id}>
        <Button size="sm" variant="danger">
          Delete
        </Button>
      </Link>
    </td>
  </tr>
);

export default class TodosList extends Component {
  refresh = () => {
    // re-renders the component
    this.setState({});
  };

  constructor(props) {
    super(props);
    this.state = { todos: [] };
  }

  componentDidMount() {
    axios
      .get("http://localhost:4000/todos/")
      .then((response) => {
        this.setState({ todos: response.data });
      })
      .catch(function (error) {
        console.log("componentDidMount axios catch error", error);
      });
  }

  todoList() {
    return this.state.todos.map(function (currentTodo, i) {
      return <Todo todo={currentTodo} key={i} />;
    });
  }

  render() {
    return (
      <div>
        <h3>
          ToDo List{" "}
          <Button
            onClick={this.refresh}
            style={{ color: "#70b5de" }}
            variant="light"
            size="sm"
          >
            <FiRefreshCw />
          </Button>
        </h3>
        <table className="table table-striped" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th>Description</th>
              <th>Responsible</th>
              <th>Priority</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>{this.todoList()}</tbody>
        </table>
      </div>
    );
  }
}

我想要 onClick={刷新组件}。努力让它正常运行。我想只刷新这个组件而不重新加载窗口,否则它会中断我的会话,导致整个应用程序重新开始。当我删除或更新数据库中的条目时,我正在调用此列表,即使它导航到页面,它也不会刷新列表。我不仅想创建一个刷新按钮,还希望在通过 this.props.history.push("/"); 调用组件时刷新组件;

【问题讨论】:

    标签: reactjs refresh setstate react-component


    【解决方案1】:

    我最初的反应是告诉你设置一个状态变量并更新它,因为这会导致重新渲染,但是在查看 react docs 之后,我想知道你是否可以调用 ReactDOM.render( ) 在你的 ToDoList 上让它与你更新的数据一起呈现。

    【讨论】:

      【解决方案2】:

      您基本上是在问(我认为),我如何重新安装此组件以便它再次调用 axios,或者更简单地说,我如何再次调用 axios 函数。您可以将 mount 内部发生的逻辑放入它自己的函数中。之后,您可以在 onClick 中调用该函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        • 2021-12-23
        • 2017-12-24
        相关资源
        最近更新 更多