Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对象作为React子对象无效(找到:具有键{username}的对象)_Javascript_Reactjs - Fatal编程技术网

Javascript 对象作为React子对象无效(找到:具有键{username}的对象)

Javascript 对象作为React子对象无效(找到:具有键{username}的对象),javascript,reactjs,Javascript,Reactjs,我开始学习React并遵循教程,当我试图上传图片时遇到了这个错误。当我按下上载按钮时,出现了这样一个错误:“对象作为React子对象无效(找到:具有键{username}的对象)。如果您想呈现子对象集合,请改用数组。”我无法再重新加载页面。 代码如下: 1.App.js import React, { useEffect, useState } from "react"; import './App.css'; import Post from './Post'; impor

我开始学习React并遵循教程,当我试图上传图片时遇到了这个错误。当我按下上载按钮时,出现了这样一个错误:“对象作为React子对象无效(找到:具有键{username}的对象)。如果您想呈现子对象集合,请改用数组。”我无法再重新加载页面。 代码如下:

1.App.js

import React, { useEffect, useState } from "react";
import './App.css';
import Post from './Post';
import { auth, db } from "./firebase";
import Modal from '@material-ui/core/Modal';
import { makeStyles } from '@material-ui/core/styles';
import { Button, Input } from "@material-ui/core";
import ImageUpload from './ImageUpload';

function getModalStyle() {
  const top = 50;
  const left = 50;

  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `translate(-${top}%, -${left}%)`,
  };
}

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),
  },
}));

function App() {
  const classes = useStyles();
  const [modalStyle] = React.useState(getModalStyle);
  const [posts, setPosts] = useState([]);
  const [open, setOpen] = useState(false);
  const [openSignIn, setOpenSignIn] = useState('');
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [user, setUser] = useState(null);
  //UseEffect -> Run a piece of code based on a specific condition

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((authUser) => {
      if (authUser) {
        //user has logged in...
        console.log(authUser);
        setUser(authUser);
      } else {
        //user has logged out...
        setUser(null);
      }

      return () => {
        //perform some cleanup action
        unsubscribe();
      }
    })
  }, [user, username]);

  useEffect(() => {
    //this is where the code runs
    db.collection('posts').onSnapshot(snapshot => {
      //everytime a new post is added, this code fires...
      setPosts(snapshot.docs.map(doc => ({
        id: doc.id,
        post: doc.data()
      })));
    })
  }, []);

  const signUp = (event) => {
    event.preventDefault();
    auth
      .createUserWithEmailAndPassword(email, password)
      .then((authUser) => {
        return authUser.user.updateProfile({
          displayName: username
        })
      })
      .catch((error) => alert(error.message))
  }


  const signIn = (event) => {
    event.preventDefault();
    auth
      .signInWithEmailAndPassword(email, password)
      .catch((error) => alert(error.message))

    setOpenSignIn(false);
  }

  return (
    <div className="app">

      {user?.displayName ? (
        <ImageUpload username={user.displayName} />
      ) : (
          <h3>Sorry you need to login to upload</h3>
        )}


      <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
              placeholder="username"
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
            <Input
              placeholder="email"
              type="text"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <Input
              placeholder="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <Button type="submit" onClick={signUp}>Sign Up</Button>
          </form>
        </div>
      </Modal>

      <Modal
        open={openSignIn}
        onClose={() => setOpenSignIn(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
              placeholder="email"
              type="text"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <Input
              placeholder="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <Button type="submit" onClick={signIn}>Sign In</Button>
          </form>
        </div>
      </Modal>

      <div className="app__header">
        <img
          className="app__headerImage"
          src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
          alt="" />
      </div>
      {user ? (
        <Button onClick={() => auth.signOut()}>Logout</Button>
      ) : (
          <div className="app__loginContainer">
            {/* : is stand for OR */}
            <Button onClick={() => setOpenSignIn(true)}>Sign In</Button>
            <Button onClick={() => setOpen(true)}>Sign Up</Button>
          </div>

        )}

      <h1>Hello Joes! Let's build an Instagram CLone with React</h1>
      {
        posts.map(({ id, post }) => (
          <Post key={id} username={post.username} caption={post.caption} imgUrl={post.imgUrl} />
        ))
      }

    </div>
  );
}

export default App;
import React,{useffect,useState}来自“React”;
导入“/App.css”;
从“./Post”导入Post;
从“/firebase”导入{auth,db}”;
从“@material ui/core/Modal”导入模态;
从'@material ui/core/styles'导入{makeStyles};
从“@material ui/core”导入{按钮,输入};
从“/ImageUpload”导入ImageUpload;
函数getModalStyle(){
常数top=50;
常数左=50;
返回{
top:`${top}%`,
左:`${left}%`,
transform:`translate(${top}%,-${left}%)`,
};
}
const useStyles=makeStyles((主题)=>({
论文:{
位置:'绝对',
宽度:400,
背景色:theme.palete.background.paper,
边框:“2px实心#000”,
boxShadow:theme.shadows[5],
填充:主题。间距(2,4,3),
},
}));
函数App(){
const classes=useStyles();
常量[modalStyle]=React.useState(getModalStyle);
const[posts,setPosts]=useState([]);
const[open,setOpen]=useState(false);
常量[openSignIn,setOpenSignIn]=useState(“”);
const[username,setUsername]=useState(“”);
const[email,setEmail]=useState(“”);
const[password,setPassword]=useState(“”);
const[user,setUser]=useState(null);
//useffect->根据特定条件运行一段代码
useffect(()=>{
const unsubscribe=auth.onAuthStateChanged((authUser)=>{
if(authUser){
//用户已登录。。。
console.log(authUser);
setUser(authUser);
}否则{
//用户已注销。。。
setUser(空);
}
return()=>{
//执行一些清理操作
取消订阅();
}
})
},[用户,用户名];
useffect(()=>{
//这就是代码运行的地方
db.collection('posts').onSnapshot(快照=>{
//每次添加新帖子时,此代码都会触发。。。
setPosts(snapshot.docs.map(doc=>({
id:doc.id,
post:doc.data()
})));
})
}, []);
常量注册=(事件)=>{
event.preventDefault();
认证
.createUserWithEmailAndPassword(电子邮件,密码)
。然后((authUser)=>{
返回authUser.user.updateProfile({
显示名称:用户名
})
})
.catch((错误)=>警报(错误消息))
}
常量符号=(事件)=>{
event.preventDefault();
认证
.使用电子邮件和密码登录(电子邮件、密码)
.catch((错误)=>警报(错误消息))
setOpenSignIn(假);
}
返回(
{user?.displayName(
) : (
抱歉,您需要登录才能上载
)}
setOpen(false)}
>
setUsername(e.target.value)}
/>
setEmail(e.target.value)}
/>
setPassword(e.target.value)}
/>
注册
setOpenSignIn(假)}
>
setEmail(e.target.value)}
/>
setPassword(e.target.value)}
/>
登录
{用户(
auth.signOut()}>注销
) : (
{/*:表示或*/}
setOpenSignIn(true)}>登录
setOpen(true)}>注册
)}
你好,Joes!让我们用React创建Instagram克隆
{
map({id,post})=>(
))
}
);
}
导出默认应用程序;
这是ImageUpload文件 2.ImageUpload.js

从'@material ui/core'导入{Button}
从“React”导入React,{useState};
从'./firebase'导入{storage,db};
从“firebase”导入firebase;
函数ImageUpload(用户名){
const[image,setImage]=useState(null);
const[progress,setProgress]=useState(0);
const[caption,setCaption]=useState(“”);
常数handleChange=(e)=>{
if(e.target.files[0]){
setImage(e.target.files[0]);
}
};
常量handleUpload=()=>{
const uploadTask=storage.ref(`images/${image.name}`).put(image);
上传任务(
“状态改变”,
(快照)=>{
//进步功能。。。
const progress=Math.round(
(snapshot.bytesttransfered/snapshot.totalBytes)*100
);
设定进度(进度);
},
(错误)=>{
//错误函数。。。
console.log(错误);
警报(错误消息);
},
() => {
//完整功能。。。
存储
.ref(“图像”)
.child(image.name)
.getDownloadURL()
。然后(url=>{
//在数据库上发布图像
db.收集(“帖子”)。添加({
时间戳:firebase.firestore.FieldValue.serverTimestamp(),
描述:描述,
imageUrl:url,
用户名:username
});
setProgress(0);
设置标题(“”);
setImage(空);
});
}
);
};
返回(
{/*我想要…*/}
{/*标题输入*/}
{/*文件选择器*/}
{/*发布按钮*/}
<progress value={progress} max="100" />
<Progress value={progress} max="100" />