如何解决当 React App 在浏览器中运行时,Material UI 组件“Modal”无限调用
这里输入图片描述我实现了material ui Modal组件之后,当App运行最后返回部分的Modal标签在浏览器中无限调用并开始消耗内存时。我认为模态组件是无限创建的。请帮忙。错误请看帖子。由于一些错误图像没有上传这个问题。 https://imgur.com/gallery/MwStlKi
这是我的进口
import { useState,useEffect } from 'react';
import './App.css';
import Post from './Post';
import { auth,db } from './Firebase.js';
import { makeStyles } from "@material-ui/core/styles";
import Modal from '@material-ui/core/Modal';
import { Button,Input } from '@material-ui/core';
这是我的主要功能
function App() {
Material UI Modal 代码
function getModalStyle()
{
const top = 50;
const left = 50;
return {
top: `${top}%`,left: `${left}%`,transform: `translate(-${top}%,-${left}%)`,};
}
MakeStyles 挂钩
const useStyles = makeStyles((theme) => ({
paper: {
position: 'absolute',width: 400,backgroundColor: theme.palette.background.paper,border: '2px solid #000',BoxShadow: theme.shadows[5],padding: theme.spacing(2,4,3),},}));
分配给对象。复制自 Material UI 网站
const classes = useStyles();
// getModalStyle is not a pure function,we roll the style only on the first render
const [modalStyle] = useState(getModalStyle);
const [open,setopen] = useState(false);
const [username,setusername] = useState('');
const [email,setemail] = useState('');
const [password,setpassword] = useState('');
const SignUp = (event)=>{
event.preventDefault();
auth.createuserWithEmailAndPassword(email,password).catch((error)=>alert(error.message))
}
const [posts,setPosts] = useState([]);
//UseEffect runs code based on specific condition
useEffect(()=>{
db.collection('post').onSnapshot(snapshot=>{
//every time database gets change fires this code
setPosts(
snapshot.docs.map(doc=>({
id: doc.id,post: doc.data()
})
)
);
})
}
);
return (
<div className="app">
这个<Modal
open={open}
onClose={()=>setopen(false)}
>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerimage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt=""/>
</center>
<Input type="text"
placeholder="username"
value={username}
onChange={(e)=>setusername(e.target.value)} />
<Input type="text"
placeholder="email"
value={email}
onChange={(e)=>setemail(e.target.value)} />
<Input type="password"
placeholder="password"
value={password}
onChange={(e)=>setpassword(e.target.value)} />
<Button type="submit" onClick={SignUp}>Sign Up</Button>
</form>
</div>
</Modal>
{/*Header*/}
<div className="app__header">
<img
className="app__headerimage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt=""
/>
<Button onClick={()=>setopen(true)}>SignUp</Button>
</div>
{/*Posts*/}
{posts.map(({id,post}) =>(
<Post key={id} userName={post.userName} imageURL={post.imageURL} captions={post.captions} />
))}
</div>
);
}
export default App;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。