我正在尝试从 api 显示一些票证信息,但由于某种原因映射不起作用
class Tickets extends React.Component {
state = {
tickets: [],
clicked: false,
};
onclicked = () => {
this.setState({ clicked: true });
console.log('helloitsme');
};
componentDidMount = async () => {
try {
const res = await getAllTickets();
this.setState({ tickets: res });
} catch (err) {}
};
render() {
return (
<article>
<section className="container">
{this.state.tickets.map((ticket) => (
<div onClick={this.onclicked} key={ticket._id}>
{this.state.clicked === true && (
<div className="boxinfo">
<h1 className="info">{ticket.date}</h1>
<h2 className="info">{ticket.place}</h2>
<h3 className="info">{ticket.price}</h3>
</div>
)}
</div>
))}
</section>
</article>
);
}
}
export default Tickets;
我用谷歌搜索并尝试更改状态数组,但没有任何效果。我应该获取 api 吗?
答案 0 :(得分:1)
仅当响应包含一些数据时才添加到状态。还要检查您的 getAllTickets 响应是否返回数组。如果响应不是数组,那么您很可能会收到此类错误。如果响应是数组,则下面的方法有效,并且在响应包含一些数据之前它不会设置状态。
class Tickets extends React.Component {
state = {
tickets: [],
clicked: false,
};
onclicked = () => {
this.setState({ clicked: true });
console.log('helloitsme');
};
componentDidMount = async () => {
try {
const res = await getAllTickets();
if (res) {
this.setState({ tickets: res });
}
} catch (err) {}
};
render() {
return (
<article>
<section className="container">
{this.state.tickets.map((ticket) => (
<div onClick={this.onclicked} key={ticket._id}>
{this.state.clicked === true && (
<div className="boxinfo">
<h1 className="info">{ticket.date}</h1>
<h2 className="info">{ticket.place}</h2>
<h3 className="info">{ticket.price}</h3>
</div>
)}
</div>
))}
</section>
</article>
);
}
}
export default Tickets;
还要检查您的响应是否包含其他一些数组数据。在这种情况下,如果您将 res.data 作为数组获取,则以下代码适合您。
class Tickets extends React.Component {
state = {
tickets: [],
clicked: false,
};
onclicked = () => {
this.setState({ clicked: true });
console.log('helloitsme');
};
componentDidMount = async () => {
try {
const { data } = await getAllTickets();
if (data) {
this.setState({ tickets: data });
}
} catch (err) {}
};
render() {
return (
<article>
<section className="container">
{this.state.tickets.map((ticket) => (
<div onClick={this.onclicked} key={ticket._id}>
{this.state.clicked === true && (
<div className="boxinfo">
<h1 className="info">{ticket.date}</h1>
<h2 className="info">{ticket.place}</h2>
<h3 className="info">{ticket.price}</h3>
</div>
)}
</div>
))}
</section>
</article>
);
}
}
export default Tickets;