在React中使用按钮过滤数据

时间:2019-06-02 23:23:16

标签: javascript reactjs

我正在尝试使用按钮来过滤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;

1 个答案:

答案 0 :(得分:2)

您需要两个数组来正确过滤数据,当您单击其中一个按钮时,它会覆盖原始数据。将<button onClick={showA()}>A</button>更改为<button onClick={() => showA()}>A</button>

// get data from api, won't change
const [polls, setPolls] = useState(null);
// used for displaying polls and filtering
const [filteredPolls, setfilteredPolls] = useState(null)

过滤数据

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() {
    setfilteredPolls(A)
}

function showB() {
    setfilteredPolls(B)
}

function showC() {
    setfilteredPolls(C)
}

显示数据

return (
  <div className="polls">
    <button onClick={() => showA()}>A</button>
    <button onClick={() => showB()}>B</button>
    <button onClick={() => showC()}>C</button>

    {
      filteredPolls && filteredPolls.map((poll) => (
        <div key={poll.id}>
          <PollCard poll={poll} />
          <hr style={{ opacity: '.1' }} />
        </div>

      ))
    }
  </div>
);

演示

<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.production.min.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">
class PollCard extends React.Component {
  render() {
    return (
      <div>{`${this.props.poll.name} - ${this.props.poll.type}`}</div>
    )
  }
}

const dpolls = [
  {
    id: 4,
    type: 'C',
    name: 'Test 1'
  },
  {
    id: 6,
    type: 'B',
    name: 'Test 2'
  },
  {
    id: 7,
    type: 'A',
    name: 'Test 3'
  },
  {
    id: 8,
    type: 'A',
    name: 'Test 9'
  },
  {
    id: 17,
    type: 'B',
    name: 'Test 39'
  }
]

function PollList() {

  const [polls, setPolls] = React.useState(null);
  const [filteredPolls, setfilteredPolls] = React.useState(null)
  const [loading, setLoading] = React.useState(false);
  const range = 30
  // var dateRange = moment().subtract(range, 'days').calendar();

  async function fetchMyAPI() {
    let response = await fetch('https://api.themoviedb.org/3/movie/upcoming?api_key=81f382d33088c6d52099a62eab51d967&language=en-US&page=1')
    const json = await response.json()
    // var data = json.filter(e => Date.parse(e.endDate) >= Date.parse(dateRange))
    setPolls(dpolls);
    setfilteredPolls(dpolls.filter(e => e.type === "A"));
    setLoading(true);

  }

  React.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() {
    setfilteredPolls(A)
  }

  function showB() {
    setfilteredPolls(B)
  }

  function showC() {
    setfilteredPolls(C)
  }
  
  function removeFiter() {
    setfilteredPolls(polls);
  }

    return (
      <div className="polls">
        <button onClick={() => showA()}>A</button>
        <button onClick={() => showB()}>B</button>
        <button onClick={() => showC()}>C</button>
        <button onClick={() => removeFiter()}>Remove Filter</button>

        {
          filteredPolls && filteredPolls.map((poll) => (
            <div key={poll.id}>
              <PollCard poll={poll} />
              <hr style={{ opacity: '.1' }} />
            </div>

          ))
        }
      </div>

    );
}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <PollList />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>