React: Concatenate string for key

隐身守侯 提交于 2020-01-03 17:06:56

问题


I am creating a list of list and want to put a unique key for each element. When I use the React Dev Tool, the new key is "2016-10,-,football".

  • Why does it have commas in it?
  • What is the correct way to specify a key when I want "2016-10-football"?

React Dev Tool Console

import React from 'react'
import ReactDOM from 'react-dom'

const dates = ['2016-10', '2016-11', '2016-12'];
const sports = ['football', 'baseball', 'basketball'];

const Dates = ( { dates, sports } ) => {
  return (
    <ul>
      { dates.map( date => {
        return (
          <div key={date.toString()}  >
            <li>{date}</li>
            <Sports sports={sports} date={date}/>
          </div>
          )
        })
      }
    </ul>
    )
}

const Sports = ( { date, sports } ) => {
  return(
    <ul>
      { sports.map( sport => {
        // Results in: key="2016-10,-,football"
        // Expected: key="2016-10-football"
        return (<li key={[date, '-', sport]} >{sport}</li>)
      })}
    </ul>
    )
}

ReactDOM.render(<Dates dates={dates} sports={sports}/>, document.getElementById('main'))

回答1:


key expects a string so when you pass an array you are calling the Array's .toString() function. You will see the same result if you do console.log([date, '-', sport].toString())

Replace [date, '-', sport] with date + '-' + sport to fix it.




回答2:


It's showing with commas because toString will use commas to join the array.

This is what you have:

arr = ['2016-10', '-', 'football']
console.log(arr.toString); // "2016-10,-,football"

This is what you want:

arr = ['2016-10', '-', 'football']
console.log(arr.join()); // "2016-10-football"

So consider replacing the li to (notice the .join()):

return (<li key={[date, '-', sport].join()} >{sport}</li>)


来源:https://stackoverflow.com/questions/40425719/react-concatenate-string-for-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!