【问题标题】:is there anyway i can define state in this case [duplicate]无论如何我可以在这种情况下定义状态[重复]
【发布时间】:2021-01-27 20:25:55
【问题描述】:

如何为列出的数据定义给定类组件的状态? PS 还是个初学者。

import React from 'react'
import { Card, Row, Col } from 'react-bootstrap'
import './AccountsCards.css'

class AccountsCards extends React.Component{
render(){

   
    const data=[
            {
                mail : 'xya@gmail.com',
                password : 'hjhjsa87',
                recovery : 'xxa@gmail.com'
            },
            {
                mail : 'xya@gmail.com',
                password : 'hjhjsa87',
                recovery : 'xxa@gmail.com'
            },
            {
                mail : 'xya@gmail.com',
                password : 'hjhjsa87',
                recovery : 'xxa@gmail.com'
            },
        ]



            return(
            data.map((listValue, i) => {
            return(
                <Card className="acard">
                    <Row className="acc-card-row">
                        <Col sm={4}>
                        {listValue.mail}
                        </Col>
                        <Col sm={4}>
                        {listValue.password}
                        </Col>
                        <Col sm={4}>
                        {listValue.recovery}
                        </Col>
                    </Row>
                </Card>
                    )    
                }
            )
        )
    }
}


export default AccountsCards

【问题讨论】:

标签: reactjs state react-props setstate


【解决方案1】:

通过像这样在 React 组件的构造函数中定义你的状态。

class AccountsCards extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [
        {
          mail: "xya@gmail.com",
          password: "hjhjsa87",
          recovery: "xxa@gmail.com"
        },
        {
          mail: "xya@gmail.com",
          password: "hjhjsa87",
          recovery: "xxa@gmail.com"
        },
        {
          mail: "xya@gmail.com",
          password: "hjhjsa87",
          recovery: "xxa@gmail.com"
        }
      ]
    };
  }

  render() {
    return this.state.data.map((listValue, i) => {
      return (
        <Card className="acard">
          <Row className="acc-card-row">
            <Col sm={4}>{listValue.mail}</Col>
            <Col sm={4}>{listValue.password}</Col>
            <Col sm={4}>{listValue.recovery}</Col>
          </Row>
        </Card>
      );
    });
  }
}

【讨论】:

  • 能否发下完整代码
  • 已更新。再次检查代码。
【解决方案2】:

在你的数据初始化下添加 state = data。

您可以通过引用this.state来调用数据。

例如

this.state.map(dataItem =&gt; {})

【讨论】:

  • 谢谢。得到解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 2011-08-08
相关资源
最近更新 更多