【问题标题】:ReactJS - TypeError: this.state.items.map is not a functionReactJS - TypeError:this.state.items.map 不是函数
【发布时间】:2020-08-30 16:31:30
【问题描述】:

作为初学者,我正在 ReactJS 中创建我的第一个项目(具有拖放功能、添加、删除和编辑的待办事项列表)。我正在尝试映射一个数组,但是当我提交文本时会出现此错误,并且代码应该将项目放入 items 数组中。

如果列表中还没有项目,这将是 UI,只有一个表单和一个用户将输入任何字符串的输入字段:

这是提交值后的错误:

这是我的当前源代码 (App.js):

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [], //This is the items array 
      currentItem: {
        text: "",
        key: "",
      },
    };
    this.handleInput = this.handleInput.bind(this);
    this.addItem = this.addItem.bind(this);
    this.deleteItem = this.deleteItem.bind(this);
    this.setUpdate = this.setUpdate.bind(this);
  }

  handleInput(e) {
    this.setState({
      currentItem: {
        text: e.target.value,
        key: Date.now(),
      },
    });
  }

  addItem(e) {
    e.preventDefault();
    const newItem = this.state.currentItem;
    console.log(newItem);
    if (newItem !== "") {
      const items = [...this.state.items, newItem];
      this.setState({
        items: newItem,
        currentItem: {
          text: "",
          key: "",
        },
      });
    }
  }

  deleteItem(key) {
    const filteredItems = this.state.items.filter((item) => item.key !== key);
    this.setState({
      items: filteredItems,
    });
  }
  setUpdate(text, key) {
    console.log("items:" + this.state.items);
    const items = this.state.items;
    items.map((item) => {
      if (item.key === key) {
        console.log(item.key + "    " + key);
        item.text = text;
      }
    });
    this.setState({
      items: items,
    });
  }

  render() {
    return (
      <div className="App">
        <DragDropContext
          onDragEnd={(param) => {
            const srcI = param.source.index;
            const desI = param.destination?.index;
            if (desI) {
              this.items.splice(desI, 0, this.items.splice(srcI, 1)[0]);
              List.saveList(this.items);
            }
          }}
        >
          <ListContainer>
            <h1>To Do List</h1>
            <form id="to-do-form" onSubmit={this.addItem}>
              <input
                type="text"
                placeholder="Enter Task"
                value={this.state.currentItem.text}
                onChange={this.handleInput}
              />
              <button type="submit"> Add </button>
            </form>
            <Droppable droppableId="droppable-1">
              {(provided, _) => (
                <div ref={provided.innerRef} {...provided.droppableProps}>
                  {this.state.items.map((item, i) => (
                    <Draggable
                      key={item.id}
                      draggableId={"draggable-" + item.id}
                      index={i}
                    >
                      {(provided, snapshot) => (
                        <ListItem
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          style={{
                            ...provided.draggableProps.style,
                            boxShadow: snapshot.isDragging
                              ? "0 0 .4rem #666"
                              : "none",
                          }}
                        >
                          <DragHandle {...provided.dragHandleProps} />
                          <span>{item.title}</span>
                        </ListItem>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </ListContainer>
        </DragDropContext>
      </div>
    );
  }
}

如何解决这个问题?我已经在构造函数的代码顶部声明了items。它说.map() 仅适用于数组,并且基于我发现的与此错误相关的其他问题,他们在字符串而不是数组中使用.map(),但在我的问题场景中明确指出items 是已经定义为一个数组。

【问题讨论】:

  • 我认为 setUpdate 函数中的 .map 没有做任何事情。 Map 返回一个新数组,您不会从该地图返回任何内容。

标签: javascript reactjs frontend


【解决方案1】:

你在 addItem 方法中犯了一个错误。您需要针对 items 键而不是新的项目字符串保存项目数组。所以将该函数更改为

addItem(e) {
    e.preventDefault();
    const newItem = this.state.currentItem;
    console.log(newItem);
    if (newItem !== "") {
      const items = [...this.state.items, newItem];
      this.setState({
        items: items, // or just items,
        currentItem: {
          text: "",
          key: "",
        },
      });
    }
  }

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2015-10-29
    • 2021-12-05
    • 2020-04-05
    • 2021-11-02
    • 2020-04-23
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多