首页 > 解决方案 > 在反应后刷新表

问题描述

发布后我想重新加载我的表格以便能够在发布后显示数据。现在问题出现了如何让我的“DataProvider”再次呈现?

我会将其作为“FormOPCConnect”中的函数调用来执行。但我不知道如何开始。我已经尝试使用“DataProvider”的“道具”,但我不知道如何呈现新表。

附上我的源代码。

TableOPCConnections.js

import React from "react";
import PropTypes from "prop-types";
import key from "weak-key";
import Table from 'react-bootstrap/Table'

const OPCVarTable = ({ data }) =>
  !data.length ? (
    <p>Nothing to show</p>
  ) : (
    <div>
      <h2 className="subtitle">
        Showing <strong>{data.length}</strong> OPC Variables
      </h2>
      <Table striped bordered hover>
        <thead>
          <tr>
            {Object.entries(data[0]).map(el => <th key={key(el)}>{el[0]}</th>)}
          </tr>
        </thead>
        <tbody>
          {data.map(el => (
            <tr key={el.id}>
              {Object.entries(el).map(el => <td key={key(el)}>{el[1]}</td>)}
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  );
OPCVarTable.propTypes = {
  data: PropTypes.array.isRequired
};

export default OPCVarTable;

数据提供者.js

import React, { Component } from "react";
import PropTypes from "prop-types";

class DataProvider extends Component {
  static propTypes = {
    endpoint: PropTypes.string.isRequired,
    render: PropTypes.func.isRequired
  };
  state = {
      data: [],
      loaded: false,
      placeholder: "Loading..."
    };
  componentDidMount() {
    fetch(this.props.endpoint)
      .then(response => {
        if (response.status !== 200) {
          return this.setState({ placeholder: "Something went wrong" });
        }
        return response.json();
      })
      .then(data => this.setState({ data: data, loaded: true }));
  }
  render() {
    const { data, loaded, placeholder } = this.state;
    return loaded ? this.props.render(data) : <p>{placeholder}</p>;
  }
}
export default DataProvider;

FormOPCConnect.js(这里我想刷新一下DataProvider的状态)

在 fetch 方法之后,只要发布到数据库成功,我想再次呈现表。

import React, { Component, useState } from "react";
import PropTypes from "prop-types";
import Button from "react-bootstrap/Button";
import Form from 'react-bootstrap/Form'
import DataProvider from "./DataProvider";

import csrftoken from './csrftoken';

class FormOPCConnect extends Component {
  constructor(props) {
    super(props);
    this.state = {
      validated: false
    };
  }
  static propTypes = {
    endpoint: PropTypes.string.isRequired
  };
  state = {
    ip_address: "",
    port: "",
    namespace_name: "",
    root_name: "",
    owner: ""
  };

  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleSubmit = event => {
    const form = event.currentTarget;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    }
    event.preventDefault();
    const { ip_address, port, namespace_name, root_name, owner } = this.state;
    const opcConn= { ip_address, port, namespace_name, root_name, owner };
    const conf = {
      method: "post",
      body: JSON.stringify(opcConn),
      headers: new Headers({ "Content-Type": "application/json", "X-CSRFTOKEN": csrftoken })
    }

    fetch(this.props.endpoint, conf).then(response => console.log(response));

    //>>
    //if response is valid -> refresh the Dataprovider and the table...
    //<<

    this.setState({ validated: this.state.validated = true })

  };

应用程序.js

const App = () => (
<React.Fragment>
<Container>
<Row>
 <Col> <NavBarTop fixed="top" /> </Col>
  </Row>
  <Row>
    <Col>  <DataProvider endpoint="opcconnection/"
                render={data => <OPCVarTable data={data} />} /></Col>
    <Col><FormOPCConnect endpoint="opcconnection/" /></Col>
  </Row>
</Container>
  </React.Fragment>
);

const wrapper = document.getElementById("app");

wrapper ? ReactDOM.render(<App />, wrapper) : null;

我是 React 新手,所以请原谅我的错误。:D

最后它看起来像这样。 OPCConnection_Image

标签: javascriptreactjsjsxreact-component

解决方案


您的代码当前包含2 个需要修复的问题,以便在您发布数据时更新您的表格。


1)DataProvider确实会在props更改时重新呈现。这里的问题是你获取你的逻辑data是在componentDidMount. componentDidMount仅在组件第一次挂载时触发,不会在重新渲染时触发。

如果您希望每次组件重新呈现时都获取数据,您可以将获取功能render放在DataProvider.

要重新渲染组件,您只需更新其props或它的state.


2)您希望在完成某些逻辑后DataProvider进行更新。FormOPCConnect

React 的问题是。您只能将变量从 传递parentschildren。您不能直接从siblingtosibling或 from childto 进行通信parent

在你的AppDataProvider是一个 sibign FormOPCConnect,他们彼此相邻。

<App> // App can communicate with every component inside it.
   <DataProvider /> // This component can't communicate with the component next to it.
   <FormOPCConnect />
</App>

这里最简单的做法是在DataProvider内部渲染FormOPCConnect并直接更新DataProvider的道具。

或者,如果这不可能,请保持App检查您的逻辑FormOPCConnect是否已完成的状态。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { boolean: false }; //state is remembered when a component updates.
  }

  flipBoolean() { //this function updates the state and rerenders App when called.
    this.setState(
      boolean: boolean!
    );
  };

  render {
    return (
      <Fragment>
        <DataProvider />
        <FormOPCConnect flipBoolean={this.flipBoolean} />
      </Fragment>
    )
  }
}

传递一个FormOPCConnect更新状态的函数App。当您希望DataProvider重新渲染时,只需flipBooleanFormOPCConnect. 这将更新statein App。这将触发App重新渲染。这将反过来重新渲染它的子DataProvider andFormOPCConnect`。

(这个变量不需要是布尔值,你可以在这里做任何你想做的事情。这个布尔值只是一个例子)。


推荐阅读