是否存在用于在数组中查找json对象的当前索引的函数?

时间:2019-05-06 10:45:44

标签: javascript reactjs

在onClick上,我想记住localStorage中的名称,但是我不知道如何从数组中发送正确的对象作为参数

myFunction(value){
    console.log(value)
    localStorage.setItem('name', value)
}

render() {
    var { isLoaded, items} = this.state;

    if (!isLoaded){
        return <div>Loading...</div>
    }else {
        return (
            <Container>

                <Jumbotron>
                    <h1 align="center">The Clinicum</h1>
                </Jumbotron>



                <Row>
                    {items.map(row =>(
                        <Col  key={row.iddoctor}>
                            <Image src= {require(`./photos/${row.photoLink}.jpg`)} 
                             roundedCircle onClick={() 
                             => this.myFunction(this.state.items.name)} />
                        </Col>
                    ))}
                </Row>

如果我使用this.state.items console.log返回孔json正确,所以其他所有工作都很好,也许是一个愚蠢的问题,但我在js中很菜鸟,我找不到答案

2 个答案:

答案 0 :(得分:1)

这样做

myFunction(value){
    console.log(value)
    localStorage.setItem('name', value)
}

render() {
    var { isLoaded, items} = this.state;

    if (!isLoaded){
        return <div>Loading...</div>
    }else {
        return (
            <Container>

                <Jumbotron>
                    <h1 align="center">The Clinicum</h1>
                </Jumbotron>



                <Row>
                    {items.map(row =>(
                        <Col  key={row.iddoctor}>
                            <Image src= {require(`./photos/${row.photoLink}.jpg`)} 
                             roundedCircle onClick={() 
                             => this.myFunction(row.name)} />
                        </Col>
                    ))}
                </Row>

答案 1 :(得分:1)

如果我理解正确,那么您想要将与单击的项目相对应的项目name保存到localStorage

一种实现方法是按如下方式修改渲染代码:

<Row>
    {items.map((row) =>(
        <Col  key={row.iddoctor}>
            <Image src= {require(`./photos/${row.photoLink}.jpg`)} 
                roundedCircle onClick={() => this.myFunction(row.name)} />
        </Col>
    ))}
</Row>

您还可以通过传递给映射回调的第二个参数访问当前呈现的row项目的索引:

<Row>
    {items.map((row, rowIndex) =>(
        <Col  key={row.iddoctor}>
            <Image src= {require(`./photos/${row.photoLink}.jpg`)} 
                roundedCircle onClick={() => this.myFunction(this.state.items[rowIndex].name)} />
        </Col>
    ))}
</Row>

希望这些指针有所帮助!