我是React的新手,我仍在尝试理解一些事情,例如我在连接到cloudinary(上传图像)的图像管理应用程序中遇到的问题:
我有以下代码:
App.js(父级)
import React, { useState } from 'react';
import './App.css';
import Gallery from './Gallery';
import TopBar from './TopBar';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
function App() {
return (
<div className="all">
<TopBar/>
<div className="gallery-enclosure">
<Gallery/>
</div>
</div>
);
}
export default App;
TopBar.js (包含上传按钮的组件,因此包含处理上传的功能
import React, { useState } from 'react';
import './App.css';
import Gallery from './Gallery'
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
function TopBar() {
const {image, setImage} = useState('')
const {loading, setLoading} = useState(false)
const uploadImage = async e => {
const files = e.target.files
const data = new FormData()
data.append('file', files[0])
data.append('upload_preset', 'projeto_react')
setLoading(true)
const res = await fetch(
'https://api.cloudinary.com/v1_1/antoniolima/image/upload',
{
method: 'POST',
body: data
}
)
const file = await res.json()
setImage(file.secure_url)
setLoading(false)
}
return (
<div className="TopBar">
<div>
<h2 id="title">
Image Management
</h2>
</div>
<div></div>
<div className="App">
<h1></h1>
<input type="file"
name="file"
accept="image/*"
id="contained-button-file"
multiple
style={{display: "none"}}
placeholder="Upload an image"
onChange={uploadImage}
/>
<label htmlFor="contained-button-file">
<Button variant="contained" color="primary" component="span">
Upload Image
</Button>
</label>
{loading ? (
<h3>Loading...</h3>
) : (
<img src={image} style={{width: '300px'}} />
)}
</div>
</div>
);
}
export default TopBar;
我很难理解的问题是,当我尝试上传文件时,出现以下错误: '未处理的拒绝(TypeError):setLoading不是函数'
但是在我将代码划分为不同的组件以使工作更有条理之前(以及为了在我的App类中创建状态和道具,因为我在使用时无法定义它们),该相同的功能起作用了一个功能组件)。
我一直在阅读有关箭头函数的信息,并将const插入箭头函数的props参数中,但是我不明白如何定义它,并且大多数访问等效于 setLoading()< / strong>在我的 TopBar.js 中,
预先感谢
答案 0 :(得分:1)
您正在破坏对象。相反,您应该使用数组解构:
const [image, setImage] = useState('')
const [loading, setLoading] = useState(false)
useState
返回数组,其中第一个索引具有状态值,第二个索引具有设置状态的函数。