gpt4 book ai didi

javascript - this.state.elements.map 不是函数

转载 作者:行者123 更新时间:2023-11-30 11:10:07 25 4
gpt4 key购买 nike

<分区>

我正在尝试在文本框中输入值,并通过设置 react 状态在单击按钮时打印它们。我正在推送数组中的对象,该对象在文本框的值正在推送但未被映射的状态下初始化。它给出错误 this.state.elements.map is not a function

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

constructor(props) {
super(props);
this.state = {
elements: [
{element1 :"A",element2: "A"},
{element1 :"B",element2: "B"},
{element1 :"C",element2: "C"},
{element1 :"D",element2: "D"}

],
}
this.elementInput = "";
this.elementInput_2 = "";

}
addItems()
{
debugger
this.setState({
elements : this.state.elements.push({
element1 : this.elementInput.value ,
element2 : this.elementInput_2.value
})

})
console.log()
}
render() {
return (
<div>
<input type="text" placeholder="Enter Element" ref={(input) => this.elementInput = input} />
<input type="text" placeholder="Enter Element" ref={(input) => this.elementInput_2 = input} />
<button onClick={this.addItems.bind(this)}>Add</button>
{
this.state.elements.map((item,index)=> {
return <p key={index}>{item.element1 + " " + item.element2}</p>
})
}
</div>
);
}
}

export default App;

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com