【问题标题】:Unable to render filtered array values in react UI无法在反应 UI 中呈现过滤后的数组值
【发布时间】:2023-03-16 22:23:02
【问题描述】:
  • 我是 React 应用程序的新手
  • 我正在尝试在 UI 中呈现过滤后的对象值数组
  • 我尝试在 onClick 函数中使用 setState 以及条件渲染的概念
  • 但在单击提交按钮后,我无法在邮政编码匹配文本字段中呈现 newArray 值
  • 你能帮助大家就这个问题提供任何可能的建议
  • 我的完整代码可在以下链接中找到 - 提供下面的代码 sn-p: https://stackblitz.com/edit/react-geum6v?file=index.js

index.js

Players Belonging to same zip code: <input type="text" name="zip_code" defaultValue = {this.state.zip1} onChange={this.handleChange}></input>
        <button onClick = {this.sports_zip_search}>Submit</button><br />
        {this.state.zip_value && <Zip />}

sports_zip_search = () => {
    var newArray = this.state.student.filter((el) => {
    return el.zip == this.state.zip1 });
    console.log(newArray);
    this.setState ({result: newArray})
    //console.log("result", this.state.result);
    this.state.zip_value = true; 
    //return (<h1>newArray</h1>)
  }

Zip.js

const Zip = (props) => {
  return(
    <h1>{ props.result }</h1>
  )
}

【问题讨论】:

  • 您在Zip 中使用了 props.result,但在渲染组件时未将任何 props 传递给组件,也未提供任何默认值

标签: javascript html reactjs


【解决方案1】:

你在这里犯了几个错误:

  1. 您正在尝试设置 zip_value,因为它是一个变量,您必须使用 setState 进行设置。
  2. 未将 result 属性传递给您的 Zip 组件。
  3. 未将生成的 prop 映射到 Zip 组件上。

建议在 react 组件中定义函数时尝试使用 camelCase 而不是 _(这也适用于状态或道具名称约定)。另外,请使用 ES6 中的 letconst 而不是 var

您的代码可能如下所示:

index.js:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import Zip from './Zip';
import { students } from './constants';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      result: [],
      zip1: "enter",
      zipValue: "false"
    }

    this.sports_zip_serach = this.sportsZipSearch.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (event) => {
    console.log("Zip Number:", event.target.value);

    this.setState({ zip1: event.target.value })
  }

  sportsZipSearch = () => {
    const { zip1 } = this.state;

    const newArray = students.filter((el) => { return el.zip === zip1 });

    console.log(zip1)
    console.log(newArray);

    this.setState({ result: newArray, zipValue: true })
  }

  render() {
    const { name, result, zip1, zipValue } = this.state;

    return (
      <div>
        <Hello name={name} />

        <h1>XYZ SPORTS COLLEGE</h1>

        <h2>PLAYER DEMOGRAPHIC DETAILS</h2>

        Players Belonging to same zip code:
         <input type="text" name="zip_code" defaultValue={zip1} onChange={this.handleChange}>
        </input>

        <button onClick={this.sportsZipSearch.bind(this)}>Submit</button><br />

        {zipValue && <Zip result={result} />}

        Number of male over certain age: <input type="number" name="age_number" value="18"></input>

        <input type="submit" value="submit"></input> <br />

        Students not from the same state: <input type="" name="state" value=""></input>

        <p>
          Start editing to see some magic happen :)
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Zip.js:

import React from 'react';

const Zip = (props) => {
  return(
    props.result.map(
      results => 
      <h1 key={results.player_first_name}>{results.player_first_name}</h1> /* This is not a perfect key, but given the values at hand */
      )
  )
}

export default Zip;

constants.js

export const students = [{
            "sports_id": "F1201",
            "player_first_name": "James",
            "Last_name": "Butt",
            "sports_address": "6649 N Blue Gum St",
            "sports_city": "New Orelans",
            "sports_county": "Orelans",
            "sports_state": "LA",
            "zip": "70111",
          },
          {
            "sports_id": "F1202",
            "player_first_name": "Josephine",
            "player_last_name": "darakjy",
            "sports_address": "6649 N Green Gum St",
            "sports_city": "New Orelans",
            "sports_county": "Orelans",
            "sports_state": "LA",
            "zip": "70116",
          },
          {
            "sports_id": "F1203",
            "player_first_name": "Joseph",
            "player_last_name": "david",
            "sports_address": "6649 N Blue Gum St",
            "sports_city": "New Orelans",
            "sports_county": "Orelans",
            "sports_state": "LA",
            "zip": "70116",
          },
          {
            "sports_id": "F1204",
            "player_first_name": "John",
            "player_last_name": "Micheal",
            "sports_address": "6649 N Blue Gum St",
            "sports_city": "New Orelans",
            "sports_county": "Orelans",
            "sports_state": "LA",
            "zip": "70116",
}];

PS:您没有任何state 呼叫“first_name”。而且,我不知道你想用最后一个&lt;input&gt; 做什么。希望对您有所帮助。

【讨论】:

  • ...感谢您的回复...我使用了上面给出的更新代码...在单击 zip 文本的提交按钮后,我仍然无法在 UI 中看到过滤后的数组值字段...你能调查一下并提供你的建议吗? Stackblitz 代码链接:stackblitz.com/edit/react-geum6v?file=index.js
  • 没问题,但您能向我解释一下代码中缺少的first_name 以及最后一个输入为空值吗?可能您希望它成为受控组件? @tamilcool
  • 我发现了这个问题并且知道你可以毫无问题地迭代抛出数组,你可以在这里找到解决方案 => stackblitz.com/edit/react-6zjvek(你的项目的一个分支)。我还将编辑我之前的回复。希望对你有帮助。
  • 感谢您的回复...效果很好..变量 first_name 和 last_name 是我错过了其他两个对象的变量,是的,我希望它是一个受控组件...我可以知道您是否使用 first_name 作为关键参数来显示名字。另外,以名字作为键本身,我也可以渲染姓氏
  • 非常感谢您的建议和回复...代码运行良好
【解决方案2】:

要更新 zip_value,您必须像用于 result

一样使用 setstate

sports_zip_search = () =&gt; {

var newArray = this.state.student.filter((el) =&gt; {

return el.sports_zip.includes(this.state.zip1)});

this.setState ({result: newArray, zip_value: "true"});

console.log("result", this.state.result);

//return (&lt;h1&gt;newArray&lt;/h1&gt;)

}

您必须在 Zip 组件中将新的结果数组作为道具传递。

Index.js 文件

{this.state.zip_value &amp;&amp; &lt;Zip result = {this.state.result}/&gt;}

并且需要迭代数组来显示每个值

Zip.js 文件

import React from 'react';

const Zip = (props) =&gt; {

// console.log())

return(

props.result.map(resultData =&gt; &lt;h1 key={}&gt;{resultData.player_first_name}&lt;/h1&gt;)

`// <h1>{  }</h1>`

)

}

export default Zip;

希望对你有帮助。

【讨论】:

  • 感谢您的回复...我明白了您的观点并使用了您上面给出的代码...单击 zip 的提交按钮后,我仍然无法在 UI 中看到过滤后的数组值文本字段...您可以查看它并提供您的建议吗? Stackblitz 代码链接:stackblitz.com/edit/react-geum6v?file=index.js
【解决方案3】:

看到这个onClick={this.sports_zip_search}

当从其他上下文调用时,此回调将具有不同的 this 值,您需要像这样将它与当前上下文绑定,因此当 sports_zip_search 将从任何地方调用时,this 将指向您的组件

onClick={this.sports_zip_search.bind(this)}

也在代码块中

this.setState ({result: newArray})
//console.log("result", this.state.result);
this.state.zip_value = true; 

同样通过setState设置zip_value

this.setState ({result: newArray, zip_value:true})

您还需要像这样将result 传递给Zip 组件

{this.state.zip_value && <Zip result={this.state.result} />}

【讨论】:

  • 感谢您的回复...我明白了您的观点并使用了上面给出的代码...单击 zip 文本的提交按钮后,我仍然无法在 UI 中看到过滤后的数组值字段...你能调查一下并提供你的建议吗? Stackblitz 代码链接:stackblitz.com/edit/react-geum6v?file=index.js
  • 见这里stackblitz.com/edit/react-rjyqcw?file=index.js 它现在似乎正在工作,你的表单实际上正在提交我删除它
  • 非常感谢您的建议和回复...代码运行良好
猜你喜欢
  • 1970-01-01
  • 2017-01-15
  • 2020-05-24
  • 1970-01-01
  • 2019-02-21
  • 2021-12-10
  • 2021-10-10
  • 2018-01-03
  • 2021-05-31
相关资源
最近更新 更多