React:映射列表并将值传递给另一个组件的props

Mor*_*len 0 reactjs

这是代码块:

export function ViewHeaders(props){
    console.log(props.pitches)
    return (
        props.pitchKeys.map((pitchKey, index) => {
            console.log(pitchKey)
            //prints as expected
            return (
                <div>
                    <h1> {pitchKey} </h1>
                    <ViewPitches pitches={props.pitches} key={pitchKey}/>
                </div>
            )
        })
    )
};


function ViewPitches(props) {
    console.log(props.key)
    // printing as undefined
    return(
        props.pitches.map((pitch, index) => {
            if (pitch.pitchName == props.key) {
                return (<div>{pitch.id}</div>)    
            }
        })
    )
}
Run Code Online (Sandbox Code Playgroud)

我正在迭代一个列表props.pitchKeys并在内部按预期ViewHeaders打印出来pitchKey.

然后我pitchKey作为道具进入ViewPitches.

但是,当我打印出来时,props.key它会以未定义的形式返回.将.map()的返回值传递给props时,是否必须执行一些特殊操作?

Tia*_*ves 6

key是一个"保留字",因此它不会作为支柱传递给您的组件,而是用于验证哪个项已更改.更改道具的名称,它应该工作.

正如React文档所说:

密钥帮助React识别哪些项目已更改,已添加或已删除.应该为数组内部的元素赋予键,以使元素具有稳定的标识