• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

알림이 1초마다 두 개씩 뜹니다.

23.10.13 19:57 작성 23.10.13 22:05 수정 조회수 686

4

분명히 코드를 그대로 따라 쳤는데 1초에 두 번씩 알림이 나오는 경우도 존재하나요?

Warning: Each child in a list should have a unique "key" prop. 오류도 떴습니다.

 

각각 notification.jsx, notificationList.jsx 코드입니다

import React from "react"

const styles = {
    wrapper: {
        margin: 8,
        padding: 8,
        display: 'flex',
        flexDirection: 'row',
        border: '1px solid grey',
        borderRadius: 16
    },
    messageText: {
        color: 'black',
        fontSize: 16
    }
}

class Notification extends React.Component {
    constructor(props) {
        super(props)

        this.state = {}
    }
    render() {
        return (
            <div style={styles.wrapper}>
                <span style={styles.messageText}>{this.props.message}</span>
            </div>
        )
    }
}

export default Notification
import React from 'react'
import Notification from './notification'

const reservedNotifications = [
    {
        message: '안녕하세요, 오늘 일정을 알려드립니다.'
    },
    {
        message: '점심식사 시간입니다.'
    },
    {
        message: '이제 곧 미팅이 시작됩니다.'
    },
    {
        message: '안녕하세요, 오늘 일정을 알려드립니다.'
    },
    {
        message: '점심식사 시간입니다.'
    },
    {
        message: '이제 곧 미팅이 시작됩니다.'
    },
    {
        message: '안녕하세요, 오늘 일정을 알려드립니다.'
    },
    {
        message: '점심식사 시간입니다.'
    },
    {
        message: '이제 곧 미팅이 시작됩니다.'
    },
    {
        message: '안녕하세요, 오늘 일정을 알려드립니다.'
    },
    {
        message: '점심식사 시간입니다.'
    },
    {
        message: '이제 곧 미팅이 시작됩니다.'
    },
    
]

var timer

class NotificationList extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            notifications: []
        }
    }

    componentDidMount() {
        const { notifications } = this.state
        timer = setInterval(() => {
            if(notifications.length < reservedNotifications.length) {
                const index = notifications.length
                notifications.push(reservedNotifications[index])
                this.setState({
                    notifications: notifications
                })
            } else {
                clearInterval(timer)
            }
        }, 1000)
    }

    render() {
        return (
            <div>
                {this.state.notifications.map(v => {
                    return <Notification message={v.message}/>
                })}
            </div>
        )
    }
}

export default NotificationList

답변 1

답변을 작성해보세요.

3

안녕하세요, 소플입니다.

해당 문제는 리액트 버전18에서 Strict Mode의 동작이 변경되었기 때문입니다.

아래 답변을 확인해보시면 도움이 되실 겁니다😀

https://www.inflearn.com/questions/619705/comment/205023

 

감사합니다.