【问题标题】:How to refetch data without refreshing the page in React graphql如何在 React graphql 中重新获取数据而不刷新页面
【发布时间】:2021-04-03 07:41:18
【问题描述】:

我是这里的新手。在下面的代码中,我使用了 React + React-Apollo。

我正在上传图像并使用 Graphql 从 db 中检索图像并将其显示在表格中

所以问题是当我上传图片时,直到我刷新页面才会显示。 单击上传按钮时,我需要显示图像。请看下面的代码

组件代码:

import React from 'react'
import axios from 'axios';
import gql from 'graphql-tag';
import {Query} from 'react-apollo';

const GET_FILES = gql`
    query getFiles{
        getFiles{
            id 
            image
            
        }
    }`;

class ImageContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            file: null
        };
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }
    onFormSubmit = (e) =>{
        e.preventDefault();
        const formData = new FormData();
        formData.append('myImage',this.state.file);
        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        };
        axios.post("http://localhost:4000/upload",formData,config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response.data.filename)
                console.log(response.data.destination)
                window.location.reload();
                this.setState({file: response.data.filename})
            }).catch((error) => {
        });
    }
    onChange = (e) => {
        this.setState({file:e.target.files[0]});
    }
    
    render() {
        return (
            <React.Fragment>
                <div className = "container">
            <form onSubmit = {this.onFormSubmit}>
                <h1>File Upload</h1>
                <input type = "file" name = "myImage" onChange = {this.onChange} />
                <button type = "submit">Upload</button>
            </form>
            <div>
            <Query query = {GET_FILES}>
                {({loading,error,data}) => {
                    if (loading) return <h4>Loading..</h4>;
                    if (error) console.log(error);
                    console.log(data)
                    return (
                        
                        <React.Fragment>
                            <div className = "row mt-3">
                                <div className = "col">
                                    <table className = "table table-striped table-primary bg-dark text-white text-center">
                                        <thead>
                                        <tr>
                                            <th>Image</th>
                                            <th></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        
                                            {
                                         data.getFiles.map(file => {
                                             return(
                                                <React.Fragment>
                                                <tr key = {file.id}>
                                             <tr>{file.image}</tr>
                                                 <td><img src = {`http://localhost:4000/${file.image}`} alt = ""/></td>
                                            
                                                 </tr>
                                                 </React.Fragment>
                                             )
                                         
                                            })
                                        }
                                        </tbody>

                                    </table>
                                </div>
                            </div>
                            
                        </React.Fragment>
                    )
                }}

            </Query>
            </div>
        </div>
    </React.Fragment>
        )
    }
}

export default ImageContainer

【问题讨论】:

  • 你的react-apollo的版本是什么

标签: reactjs react-apollo


【解决方案1】:

您可以使用 refetch 提供的 Query 组件道具

import React from 'react'
import axios from 'axios';
import gql from 'graphql-tag';
import {Query} from 'react-apollo';

const GET_FILES = gql`
  query getFiles {
      getFiles{
          id
          image
      }
  }
`;

class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            file: null
        };
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onFormSubmit = (evt) => {
        evt.preventDefault();
        const formData = new FormData();
        formData.append('myImage',this.state.file);

        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        };

        axios.post("http://localhost:4000/upload", formData, config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response.data.filename)
                console.log(response.data.destination)
                window.location.reload();
                this.setState({
                  file: response.data.filename
                }, () => {
                  this.query_refetch && this.query_refetch(); // refetch function called
                })
            }).catch((error) => {
        });
    }
    onChange = (e) => {
        this.setState({file:e.target.files[0]});
    }

    render() {
        return (
            <React.Fragment>
                <div className = "container">
                    <form onSubmit = {this.onFormSubmit}>
                        <h1>File Upload</h1>
                        <input type = "file" name = "myImage" onChange = {this.onChange} />
                        <button type = "submit">Upload</button>
                    </form>
                    <div>
                      <Query query={GET_FILES}>
                          {({loading, error, data, refetch}) => {

                              this.query_refetch = refetch; // refetch function assigned

                              if (loading) return <h4>Loading..</h4>;
                              if (error) console.log(error);
                              console.log(data)
                              return (
                                  <React.Fragment>
                                      <div className = "row mt-3">
                                          <div className = "col">
                                              <table className = "table table-striped table-primary bg-dark text-white text-center">
                                                  <thead>
                                                      <tr>
                                                          <th>Image</th>
                                                          <th></th>
                                                      </tr>
                                                  </thead>
                                                  <tbody>
                                                    {data.getFiles.map(file => {
                                                      return (
                                                        <React.Fragment>
                                                            <tr key = {file.id}>
                                                            <tr>{file.image}</tr>
                                                              <td>
                                                                  <img src = {`http://localhost:4000/${file.image}`} alt=""/>
                                                              </td>
                                                            </tr>
                                                        </React.Fragment>
                                                      );
                                                    })}
                                                  </tbody>
                                              </table>
                                          </div>
                                      </div>
                                  </React.Fragment>
                              )
                          }}
                      </Query>
                  </div>
              </div>
          </React.Fragment>
        )
    }
}

export default ImageContainer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2019-05-28
    • 2023-02-26
    • 2013-07-18
    • 2016-12-01
    • 2021-01-07
    • 2016-04-18
    相关资源
    最近更新 更多