React:映射数据

我正在尝试映射数组中的数据,但是,当我运行代码时,数据并未映射。如果我记录数据(序列变量),它会记录我想要映射的变量(下面的屏幕截图)。有人对为什么数据没有映射有任何建议吗?


numberList() {

  const uid = this.state.user.uid;

    const serialRef = db.ref(uid + "/serials");

    

    serialRef.on("value", (serial_numbers)=> {

      const serials = [];

      serial_numbers.forEach((serial_number)=> {

        serials.push({s:serial_number.val()});

      });

      console.log(serials);

  return (

    <div>

      {serials.map((number) => <Card>

      <Card.Body>{number.s.serial}</Card.Body> </Card>)}

    </div>

  );

    });


}

        render (){

        return (

          <button onClick={this.numberList}>Cards</button>

        )};


}

http://img.mukewang.com/64b8e7700001be9804110338.jpg

慕姐8265434
浏览 130回答 2
2回答

万千封印

您没有从组件中渲染任何内容在处理数组之后,理想情况下,您应该将其设置为会导致组件重新渲染的状态,并且如果您从如下状态渲染序列,它将在加载后显示。单击按钮后,数字列表函数将执行并使用数据设置状态,并将其映射和显示。根据您当前的代码,您只需映射并返回未在任何地方使用的项目,因此您应该遵循以下模式。class Serials extends Component {&nbsp; state = {&nbsp; &nbsp; serials: [],&nbsp; };&nbsp; numberList() {&nbsp; &nbsp; const uid = this.state.user.uid;&nbsp; &nbsp; const serialRef = db.ref(uid + '/serials');&nbsp; &nbsp; serialRef.on('value', (serial_numbers) => {&nbsp; &nbsp; &nbsp; const serials = [];&nbsp; &nbsp; &nbsp; serial_numbers.forEach((serial_number) => {&nbsp; &nbsp; &nbsp; &nbsp; serials.push({ s: serial_number.val() });&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; this.setState({ serials: serials });&nbsp; &nbsp; });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.numberList}>Cards</button>&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {this.state.serials.map((number) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Card>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Card.Body>{number.s.serial}</Card.Body>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Card>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}

叮当猫咪

serials应该是组件状态的一部分,由单击处理程序更新,并映射到方法中render。state = {&nbsp; serials: [],};...numberList() {&nbsp; const { user: { uid } } = this.state;&nbsp; const serialRef = db.ref(uid + "/serials");&nbsp; serialRef.on("value", (serial_numbers)=> {&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; serials: serial_numbers.map(s => ({ s: s.val() })),&nbsp; &nbsp; });&nbsp; });}...render () {&nbsp; const { serials } = this.state;&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button onClick={this.numberList}>Cards</button>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {serials.map((number) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Card>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Card.Body>{number.s.serial}</Card.Body>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Card>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; )};}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript