简体   繁体   中英

Error of anonymous function in React-Native

import React, { forwardRef } from "react";
import { Card, CardContent, Typography } from "@material-ui/core";
import './Message.css';

const Message = forwardRef(({ message, username }, ref) => {
    const isUser = username === message.username;

    return (

        <div ref={ref} className={`message ${isUser && "message_user"}`}>
            <Card className={isUser ? "message_userCard" : "message_guestCard"}>
                <CardContent>
                    <Typography
                        color="white"
                        variant="h5"
                        component="h2"
                     >
                        {message.username}: {message.message}
                    </Typography>
                </CardContent>
            </Card>
        </div>
    )
})

export default Message

I don't know what to do, my console keeps returning: TypeError: Cannot read property 'username' of undefined (anonymous function) src/Message.js:6 ▶ 16 stack frames were collapsed.

Change the const sendMessage part with this code at app.js. It will fix

Actually the problem is you have to delete or comment this line at app.js

/*setMessages([...messages, { username: username, message: input }]);*/
const sendMessage = (event) => {
        
        event.preventDefault(); // prevent form to refresh the page

        db.collection("messages").add({
            username: username,
            message: input,
            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        });

        /* setMessages([...messages, { username: username, message: input }]);*/
        setInput("");
    };

Faced the same problem here's the solution. You just have to remove everything that you've had written before in the array of useState in the App.js file. Before you had it mostly like this:

const [messages, setMessages] = useState([{}]);

Now it should look like this:

const [messages, setMessages] = useState([]);

You're confused yourself const isUser = username === message.username . What I will do here.

create hook.

const Message = forwardRef(({ message, username }, ref) => {
    const [isUser, setIsUser] = useState(false)
    username === message.username ? setIsUser(true) : setIsUser(false)
  return(
       <div>
          {isUser? <div>True</div> : <div>False</div>}
       </div>
      )

Feel free to ask question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM