我很难将 React 类组件转换为钩子(Hook)。 自从我玩 React 以来已经有一段时间了,所以我无法掌握它。
我的代码试图做的是上传图像并将其放入 firebase 存储并显示它。 它适用于类组件,但我无法将它们转换为 Hook 。 有人可以帮我吗???
import React, {Component} from 'react';
import fire from '../config/Fire';
import FileUploader from 'react-firebase-file-uploader';
import firebase from 'firebase';
class Fileupload extends Component {
state = {
image: '',
imageURL: '',
progress: 0
}
handleUploadStart = () => {
this.setState({
progress: 0
})
}
handleUploadSuccess = filename => {
this.setState ({
image: filename,
progress: 100
})
fire.storage().ref('avatars').child(filename).getDownloadURL()
.then(url => this.setState({
imageURL: url
}))
}
render() {
console.log("this.state", this.state)
console.log("this.state.imageURL",this.state.imageURL)
return (
<div className="App">
<h2>file upload and load</h2>
<FileUploader
accept="image/*"
name='image'
storageRef={fire.storage().ref('avatars')}
onUploadStart = {this.handleUploadStart}
onUploadSuccess = {this.handleUploadSuccess}
/>
<div>
<h4>show image</h4>
<img src={this.state.imageURL} />
</div>
</div>
);
};
}
export default Fileupload;
最佳答案
在将类重构为钩子(Hook)时,需要牢记几件事。
- 而不是 Class
使用 function()
或 () => 箭头函数
,
- 没有渲染函数只有一个返回语句,
- this
关键字仅用于将函数和状态绑定(bind)到 Class
。这些不用于功能,
- 你应该使用 useState
钩子(Hook)而不是 this.setState
。
import React, { useState } from 'react';
import fire from '../config/Fire';
import FileUploader from 'react-firebase-file-uploader';
import firebase from 'firebase';
function Fileupload() {
const [image, setImage] = useState('');
const [imageURL, setImageUrl] = useState('');
const [progress, setProgress] = useState(0);
const handleUploadStart = () => {
setProgress(0);
};
const handleUploadSuccess = filename => {
setImage(filename);
setProgress(100);
fire
.storage()
.ref('avatars')
.child(filename)
.getDownloadURL()
.then(url => setImageUrl(url));
};
return (
<div className="App">
<h2>file upload and load</h2>
<FileUploader
accept="image/*"
name="image"
storageRef={fire.storage().ref('avatars')}
onUploadStart={handleUploadStart}
onUploadSuccess={handleUploadSuccess}
/>
<div>
<h4>show image</h4>
<img src={imageURL} />
</div>
</div>
);
}
export default Fileupload;
关于javascript - 如何将 react 类转换为 react 钩子(Hook)(firebase 存储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212458/