javascript - 过滤器 JSON 不起作用

标签 javascript reactjs react-native

如何使用 http.get 过滤来自一个 JSON 调用的数据? 控制台说:

TypeError: Cannot read property 'toLowerCase' of undefined

使用 Angular 可以轻松完成一次管道服务并完成,但使用 ReactJS 很多事情都很复杂。

import React, { Component } from 'react';

import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function searchingData(product) {
  return function(x){
    return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
  }
}

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
        items : [],
        product: ''
    };
    this.componentWillMount = this.componentWillMount.bind(this);
  }

  componentWillMount() {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => res.json())
      .then( data => this.setState({ items : data }) );
  }

  SearchWord(event) {
    this.setState({
      product: event.target.value
    })
  }

  render() {

    const {items, product} = this.state;

    return (
      <Router> 
        <div className="App">  

          {/* SHOW JSON */}

          <input type="text" placeholder="SEARCH DATA" onChange={this.componentWillMount} value="{product}" /> 

          <ul>
            {
              items.filter(searchingData(product)).map(item =>
                <li key={item.title}>
                    {item.title}
                </li>
            )}
          </ul>        

        </div>
      </Router>
    );
  }
}

export default App;

最佳答案

当您的 x 或第一个为 null 时,应该会发生这种情况

 return function(x){
    if(x && x.first != null){
    return x.first.toLowerCase().includes(product.toLowerCase()) || !product;
    }else
    return x;
  }

绑定(bind)时也不需要使用引号“”

value={product}

关于javascript - 过滤器 JSON 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071564/

相关文章:

reactjs - 处理同一元素的 React onDoubleClick 和 single onClick

javascript - 将 React 上下文提供者的状态放入 const 中

ios - React Native - iOS - 无效的 `Podfile` 文件 : undefined method `[]' for nil:NilClass

javascript - 如何在对象中添加项目?

javascript - 将返回值从 php 传递给 js

reactjs - ant design 中对 dataSource 执行过滤函数后,获取组件表中过滤后的数据

javascript - 在 Aurelia 中添加服务人员

android - React native - 开发服务器返回 respose 错误代码 :404

javascript - JavaScript 中等待 AJAX 的首选方法

javascript - AngularJS : promise chain not deferring past 2nd function