我正在尝试使用按钮来过滤 JSON 中的数据。每当单击按钮时,它将使用过滤后的 JSON 数据更新状态。然后它将返回包含更新数据的列表。现在我有四个按钮来过滤四种不同的“类型”,但代码根本不起作用。import React, { useState, useEffect } from 'react';import * as moment from 'moment';import PollCard from './PollCard'function PollList() { const [polls, setPolls] = useState(null); const [loading, setLoading] = useState(false); const range = 30 var dateRange = moment().subtract(range, 'days').calendar(); async function fetchMyAPI() { let response = await fetch(url) const json = await response.json() var data = json.filter(e => Date.parse(e.endDate) >= Date.parse(dateRange)) setPolls(data.reverse()) setLoading(true); } useEffect(() => { fetchMyAPI(); }, []) if (!loading) { return ("Loading...") } var A = polls.filter(e => e.type === "A") var B = polls.filter(e => e.type === "B") var C = polls.filter(e => e.type === "C") function showA() { setPolls(A) } function showB() { setPolls(B) } function showC() { setPolls(C) } return ( <div className="polls"> <button onClick={showA()}>A</button> <button onClick={showB()}>B</button> <button onClick={showC()}>C</button> { polls && polls.map((poll) => ( <div key={poll.id}> <PollCard poll={poll} /> <hr style={{ opacity: '.1' }} /> </div> )) } </div> );}export default PollList;
添加回答
举报
0/150
提交
取消