【问题标题】:.map() is mapping the wrong value to my header tags.map() 将错误的值映射到我的标题标签
【发布时间】:2019-09-13 14:11:28
【问题描述】:

我正在创建一个应用程序,允许员工从我们的商店预订设备。当我们单击“预订”按钮时,我正在使用 reactstrap 打开一个模式,以便员工可以添加更多信息。当模态打开时,我想要模态标题中的项目名称,但由于某种原因,当我使用.map() 时,它为所有模态提供相同的标题,但.map() 是否适用于其他所有内容?

为了节省您的时间,只有这部分代码会发生错误:

<ModalHeader toggle={this.toggle}>
  {item.name}
</ModalHeader>

我不确定问题出在哪里,希望能得到任何帮助!

{events.map(item => {
  if (item.isBooked === true) {
    return (
      <div className="col-md-4 item p-2">
        <img className="item-img-booked" src={item.img} alt="" />
        <br />
        <br />
        <h6 className="text-center">{item.name}</h6>
        <button className="btn btn-success btn-sm m-1">Return</button>
      </div>
    );
  } else
    return (
      <div className="col-md-4 item p-2">
        <img className="item-img" src={item.img} alt="" />
        <br />
        <br />
        <h6 className="text-center">{item.name}</h6>
        <Button color="danger" onClick={this.toggle}>
          Book Out
        </Button>
        <div>
          <Modal isOpen={this.state.modal} toggle={this.toggle}>
            <ModalHeader toggle={this.toggle}>
              {item.name}
            </ModalHeader>
            <ModalBody>
              Lorem ipsum dolor sit amet, consectetur adipisicing
              elit, sed do eiusmod tempor incididunt ut labore et
              dolore magna aliqua. Ut enim ad minim veniam, quis
              nostrud exercitation ullamco laboris nisi ut aliquip ex
              ea commodo consequat. Duis aute irure dolor in
              reprehenderit in voluptate velit esse cillum dolore eu
              fugiat nulla pariatur. Excepteur sint occaecat cupidatat
              non proident, sunt in culpa qui officia deserunt mollit
              anim id est laborum.
            </ModalBody>
            <ModalFooter>
              <Button color="primary" onClick={this.toggle}>
                Confrim
              </Button>
              {" "}
              <Button color="secondary" onClick={this.toggle}>
                Cancel
              </Button>
            </ModalFooter>
          </Modal>
        </div>
      </div>
    );
  }
)}

【问题讨论】:

  • .map() 使用数组中的数据,如果标题错误,则可能数组中的标题名称错误。
  • @JuniusL。不幸的是,事实并非如此。名称在数组中是正确的。您可以看到我在同一个映射中两次使用 {item.name}。一次按预期工作,另一次使用数组中最后一项的名称
  • 请在这里创建一个简单的工作项目来解决您的问题stackblitz.com
  • @JuniusL。这是链接:react-us21xi.stackblitz.io/events 我无法让 reactstrap 工作......
  • 我想看代码,代码在哪里?

标签: javascript reactjs reactstrap


【解决方案1】:

不要为每个项目创建一个模式,而是将模式移到.map() 之外并将您的项目保存在该状态中。将每个项目的索引传递给toggle 函数并使用该索引从this.state.events[index] 等状态的事件中获取项目的名称。您的模式将从状态中提取名称。

import React, { Component } from "react";
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";

export class EventsAll extends Component {
  state = {
    modal: false,
    index: -1,
    events: [],
    name: ""
  };

  toggle = index => {
    const ind = typeof index !== "number" ? -1 : index;

    this.setState(
      prevState => ({
        modal: !prevState.modal,
        index: ind
      }),
      () => {
        this.populateModalData();
      }
    );
  };

  populateModalData = () => {
    if (this.state.index < 0 || typeof this.state.index !== "number") {
      return;
    }

    const item = this.state.events[this.state.index];

    this.setState({
      name: item.name
    });
  };

  componentDidMount = () => {
    const { events } = this.props.events;

    this.setState({
      events: events
    });
  };

  render() {
    return (
      <div>
        <div className="row">
          {this.state.events.map((item, index) => {
            if (item.isBooked === true) {
              return (
                <div className="col-md-4 item p-2">
                  <img className="item-img-booked" src={item.img} alt="" />
                  <br />
                  <br />
                  <h6 className="text-center">{item.name}</h6>
                  <button className="btn btn-success btn-sm m-1">Return</button>
                </div>
              );
            } else
              return (
                <div className="col-md-4 item p-2">
                  <img className="item-img" src={item.img} alt="" />
                  <br />
                  <br />
                  <h6 className="text-center">{item.name}</h6>
                  <Button
                    val={index}
                    color="danger"
                    onClick={() => this.toggle(index)}
                  >
                    Book Out
                  </Button>
                  <div />
                </div>
              );
          })}
        </div>

        <Modal isOpen={this.state.modal} toggle={this.toggle}>
          <ModalHeader toggle={this.toggle}>{this.state.name}</ModalHeader>
          <ModalBody>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
            eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
            ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
            aliquip ex ea commodo consequat. Duis aute irure dolor in
            reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
            pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
            culpa qui officia deserunt mollit anim id est laborum.
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={this.toggle}>
              Confrim
            </Button>{" "}
            <Button color="secondary" onClick={this.toggle}>
              Cancel
            </Button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

export default EventsAll;

working demo

【讨论】:

  • 完美!感谢您的帮助:)
【解决方案2】:

我猜你的切换功能会同时切换所有模式,所以无论你在哪里点击,只有最后一个模式对你可见。

尝试使用数组来切换模态可见性状态。

【讨论】:

  • 你是 100% 正确的。当我删除 reactstrap cdn 并单击按钮时,它显示了所有模式。但是我将如何使用数组来解决这个问题呢?很抱歉,如果我觉得我很菜鸟,我仍然是一个非常初级的开发人员。
【解决方案3】:

我没有完全阅读您的问题,但从标题中我猜您的问题是您没有为组件使用 key 属性,并且当 item.isBooked 更改时,您的组件不会更改为好吧。

所以,试试这个: 将 events.map(item =&gt; { 更改为 events.map((item, index) =&gt; { 以便在每次 map 呈现来自 events 的项目时生成唯一密钥。 对于您的divs 内部返回函数,请执行以下操作: &lt;div className="col-md-4 item p-2" key={index}&gt; &lt;div className="col-md-4 item p-2" key={index}&gt;

【讨论】:

  • 所以问题是切换功能为我的数组中的每个对象打开了一个模式。所以它实际上是正确映射的,但是因为它为每个项目创建了一个模态,我只能看到数组中最后一个项目的模态,因为它涵盖了其余部分。现在我正试图找到一种方法让我的切换功能只打开一个模式。
  • 'keys' 是 React 知道何时重新渲染元素的方式。传递索引几乎总是错误的。例如:您传递一个数组:它呈现,然后您对数组进行排序,元素的索引不会改变(第一个元素将始终为 0),因此不会重新呈现。
  • @J.Hansen 确切地说,但正如 Pierre 提到的那样,使用地图索引并不是那么明智,但我告诉你使用它的原因是我没有看到你的代码,我没有不知道用作密钥的任何其他唯一数据。
猜你喜欢
  • 2021-09-03
  • 1970-01-01
  • 2013-10-13
  • 2015-07-16
  • 2016-05-04
  • 2012-04-02
  • 2020-08-09
  • 2017-05-04
  • 2017-11-11
相关资源
最近更新 更多