React过滤状态而不改变数组

时间:2020-01-13 03:26:34

标签: javascript reactjs filter

我知道我犯了一个愚蠢的错误,但是我似乎无法弄清楚这是什么。我有一个状态列表,根据用户从下拉列表中选择的内容,状态会更新。但是我以某种方式改变了状态,因此当用户第二次选择某项时,列表显示为空,屏幕上没有任何显示。

这似乎是一个很普遍的问题,我已经检查了hereherehere

import React, { Component } from 'react';
import axios from 'axios';
import Sidebar from './components/Sidebar'
import Map from './components/Map'

require('dotenv').config();

class App extends Component {
  state = {
    incidents: [],
    map: false,
    options: []
  }

  async componentDidMount() {
    const res = await axios.get('https://data.sfgov.org/resource/wr8u-xric.json', {
      params: {
        "$limit": 500,
        "$$app_token": process.env.APP_TOKEN
      }
    })

    const incidents = res.data;
    this.setState({ incidents });

    console.log(incidents)

    this.getOptions()
  };

  getMap = () => {
    this.setState({ map: true });
    console.log(this.state.options)
  }

  handleChange = (e) => {
    const items =  this.state.incidents.filter(incident => incident['zip_code'] === e.target.value)
    this.setState({incidents: items})
  }

  getOptions = () => {
    this.state.incidents.map(incident => {
      if(!this.state.options.includes(incident['zip_code'])){
        this.state.options.push(incident['zip_code'])
      }
    })
  }

  render() {
    return (
      <div>
        <h1> San Francisco Fire Incidents</h1>
        <button onClick={this.getMap}> Get Map</button>

        <div id="main">
          <div style={{ width: '20%', height: '900px', display: 'inline-block', overflow: 'scroll', marginRight: '2px' }}>
            <span> Zip Code</span>
            <form>
              <select value={this.state.value} onChange={this.handleChange}>
              {this.state.options.map(option => (
                <option value={option} key={option}>{option}</option>
              ))}

              </select>
            </form>
          </div>
          {
            this.state.map ? <Map incidents={this.state.incidents} /> : ''
          }
        </div>
      </div>
    );
  }
}

export default App;

3 个答案:

答案 0 :(得分:2)

问题是您没有在任何地方维护初始状态。

因此,在更改状态并删除项目之后,可以预期状态变量将不包含所有原始项目。

更改为以下内容:

import React, { Component } from 'react';
import axios from 'axios';
import Sidebar from './components/Sidebar'
import Map from './components/Map'

require('dotenv').config();

class App extends Component {
  state = {
    initialIncidents: [], 
    incidents: [],
    map: false,
    options: []
  }

  async componentDidMount() {
    const res = await axios.get('https://data.sfgov.org/resource/wr8u-xric.json', {
      params: {
        "$limit": 500,
        "$$app_token": process.env.APP_TOKEN
      }
    })

    const incidents = res.data;
    this.setState({ initialIncidents: incidents });

    console.log(incidents)

    this.getOptions()
  };

  getMap = () => {
    this.setState({ map: true });
    console.log(this.state.options)
  }

  handleChange = (e) => {
    const items =  this.state.initialIncidents.filter(incident => incident['zip_code'] === e.target.value)
    this.setState({incidents: items})
  }

  getOptions = () => {
    this.state.incidents.map(incident => {
      if(!this.state.options.includes(incident['zip_code'])){
        this.state.options.push(incident['zip_code'])
      }
    })
  }

  render() {
    return (
      <div>
        <h1> San Francisco Fire Incidents</h1>
        <button onClick={this.getMap}> Get Map</button>

        <div id="main">
          <div style={{ width: '20%', height: '900px', display: 'inline-block', overflow: 'scroll', marginRight: '2px' }}>
            <span> Zip Code</span>
            <form>
              <select value={this.state.value} onChange={this.handleChange}>
              {this.state.options.map(option => (
                <option value={option} key={option}>{option}</option>
              ))}

              </select>
            </form>
          </div>
          {
            this.state.map ? <Map incidents={this.state.incidents} /> : ''
          }
        </div>
      </div>
    );
  }
}

export default App;

答案 1 :(得分:0)

我认为这部分有问题

getOptions = () => {
this.state.incidents.map(incident => {
  if(!this.state.options.includes(incident['zip_code'])){
    this.state.options.push(incident['zip_code'])
  }
})

}

搜索时,您总是在改变状态选项。如果找不到结果,则options数组将为空。

尝试做这样的事情。

  getOptions = () => {
    let options = [...this.state.options]
    this.state.incidents.map(incident => {
      if(!this.state.options.includes(incident['zip_code'])){
        options.push(incident['zip_code'])
      }
    })
    this.setState({options});
  }

答案 2 :(得分:0)

this.state.incidents包含所有事件,并且当用户进行第一选择时,您正在更改incidents数组。 第二个选择是从第一个选择中过滤已过滤的事件,然后返回empty。这可能是导致此问题的原因。

  const items =  this.state.originalIncidents.filter(incident => incident['zip_code'] === e.target.value)
    this.setState({incidents: items})