gpt4 book ai didi

reactjs - 错误 : Objects are not valid as a React child (found: object with keys {id, 名称})

转载 作者:行者123 更新时间:2023-12-04 00:59:13 30 4
gpt4 key购买 nike

我在编译我的 reactJS 组件时遇到问题:

import React, { Component } from "react";

class StatefullComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{ id: 1, name: "Perceuse" },
{ id: 2, name: "disqueuse" },
{ id: 3, name: "marteau" },
{ id: 4, name: "clé de 17" },
{ id: 5, name: "meuleuse" }
],
newItem: ""
};
this.addNewItemToState = this.addNewItemToState.bind(this);
this.handleChange = this.handleChange.bind(this);
this.removeThisItem = this.removeThisItem.bind(this);
}

sortItems() {
this.setState({
items: this.state.items.sort()
});
}

addNewItemToState() {
this.setState({
items: [...this.state.items, this.state.newItem],
newItem: ""
});
}

removeThisItem(bidule) {
const tmparray = this.state.items.filter(bazar => {
return bazar.id !== bidule;
});
console.log(tmparray);
this.setState({
items: tmparray
});
}

handleChange(e) {
this.setState({
newItem: e.target.value
});
}

render() {
return (
<div className="statefull">
<h2>Satefull component, build with a class</h2>
<ul>
{this.state.items.map(item => (
<li className="lambda">
{item}
<button onClick={this.removeThisItem(item.id)}>
supprimer cet item
</button>
</li>
))}
</ul>
<input
type="text"
placeholder="Ajouter un element"
value={this.state.newItem}
onChange={this.handleChange}
/>
<button onClick={this.addNewItemToState}>Ajouter</button>
</div>
);
}
}

export default StatefullComponent;

和我的 App.js:

import "./App.scss";
import React from "react";
import StatelessComponent from "./components/stateless-component";
import StatefullComponent from "./components/statefull-component";

function App() {
return (
<div className="App">
<StatefullComponent />
</div>
);
}

export default App;

为什么会出现此错误?

'Error: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.'

我是否在我的状态下错误地格式化了我的项目数组?拥有一个 id 对我来说很重要,因为我希望能够删除一个项目。有什么线索吗?谢谢。

最佳答案

那是因为您正试图在 map 中呈现一个对象。将您的 ul 更改为:

<ul>
{
this.state.items.map((item, index) => <li className="lambda" key={index}>{item.name}<button onClick={this.removeThisItem(item.id)}>supprimer cet item</button></li>)
}
</ul>

希望这对你有用。

关于reactjs - 错误 : Objects are not valid as a React child (found: object with keys {id, 名称}),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59984233/

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