본문으로 바로가기
반응형

each child in an array or iterator should have a unique key prop solution


현재 React Native로 앱을 만들고 있다.

지금은 댓글 리스트를 prop로 받고 해당 prop을 state에 저장하고 작업을 하고 있는데


와 같은 에러가 발생했다.

눌러서 자세한 내용을 확인해봤다.



댓글 리스트는 Array라서 쉽게 랜더링 해주기 위해 map을 사용하고 있다.

검색해보니 map을 사용할 때는 key속성을 줘야 한다고 나와있다.

먼저 아래와 같은 코드가 있다고 가정한다.


    const commentList = this.state.commentList.map((data) => {

      return (

        <View style={styles.commentView}>

          <View style={styles.commentHeader}>

            <Avatar

            small

            rounded

            title={data.userkey.username}

            activeOpacity={0.7}

            />

          </View>

          <View style={styles.commentBody}>

            <Card>

              <CardItem header style={{marginBottom: -15}}>

                <Text style={{fontWeight: 'bold'}}>{data.userkey.username}</Text>

              </CardItem>

              <CardItem>

                <Text>{data.content}</Text>

              </CardItem>

            </Card>

          </View>

        </View>

      )


위 소스를 아래와 같이 수정하면 된다. 바꾼 부분은 Bold처리로 표시함.


    const commentList = this.state.commentList.map((data, i) => {

      return (

        <View style={styles.commentView} key={i}>

          <View style={styles.commentHeader}>

            <Avatar

            small

            rounded

            title={data.userkey.username}

            activeOpacity={0.7}

            />

          </View>

          <View style={styles.commentBody}>

            <Card>

              <CardItem header style={{marginBottom: -15}}>

                <Text style={{fontWeight: 'bold'}}>{data.userkey.username}</Text>

              </CardItem>

              <CardItem>

                <Text>{data.content}</Text>

              </CardItem>

            </Card>

          </View>

        </View>

      )


key속성에 인덱스를 박아주면 해결된다.

반응형