【发布时间】: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