我如何在reactjs中将数据设置为状态

问题描述 投票:1回答:3

由于我是React的新手,所以我使用了filter和map从数组列表中选择数组。我得到了预期的输出。现在我想通过呈现值设置this.state.search。我该怎么办?这是下面我的代码的图片:

import React, { Component } from 'react';
import { NativeSelect } from '@material-ui/core';

export default class Test extends Component {
constructor() {
    super();
    this.state = {
        people: [
            {
                address: "Biratnagar",

                bank: "Nabil Bank",

                bankaccountnumber: 34343434,

                baselocation: "Kathmandu",

                basicpay: 5000,

                branch: "telecom",

                class: "class1",

                confirmpassword: "nabanit123",

                degree: "master",

                designation: "engineer",

                email: "[email protected]",

                id: "5e9fdebf0178920ed082241f",

                mobilenumber: 445454545,

                name: "Nabanit Koirala",

                password: "nabanit123",

                salary: 20000
            },
            {
                address: "Biratnagar",

                bank: "Nabil Bank",

                bankaccountnumber: 34343434,

                baselocation: "Kathmandu",

                basicpay: 5000,

                branch: "telecom",

                class: "class1",

                confirmpassword: "nabanit123",

                degree: "master",

                designation: "engineer",

                email: "[email protected]",

                id: "5e9fdebf0178920ed082241f",

                mobilenumber: 445454545,

                name: "saroj kumar",

                password: "nabanit123",

                salary: 30000
            },
            {
                address: "Biratnagar",

                bank: "Nabil Bank",

                bankaccountnumber: 34343434,

                baselocation: "Kathmandu",

                basicpay: 5000,

                branch: "Account",

                class: "class1",

                confirmpassword: "nabanit123",

                degree: "master",

                designation: "engineer",

                email: "[email protected]",

                id: "5e9fdebf0178920ed082241f",

                mobilenumber: 445454545,

                name: "kamlesh shresths",

                password: "nabanit123",

                salary: 5000
            },
            {
                address: "Biratnagar",

                bank: "Nabil Bank",

                bankaccountnumber: 34343434,

                baselocation: "Kathmandu",

                basicpay: 5000,

                branch: "IT",

                class: "class1",

                confirmpassword: "nabanit123",

                degree: "master",

                designation: "engineer",

                email: "[email protected]",

                id: "5e9fdebf0178920ed082241f",

                mobilenumber: 445454545,

                name: "kumar thapa",

                password: "nabanit123",

                salary: 50000
            },
        ],
        name: '',
        isLoading: true,
        search: ''
    }
}
handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({
        [name]: value
    })
}
handleSubmit = (e) => {
    e.preventDefault();

    this.setState({
        isLoading: false


    })

    console.log("handle submit>>", this.state);
}
componentDidMount() {
    this.setState({
        search: Test
    })

}

render() {
    console.log("component did mount>>", this.state);
    const { search } = this.state;
    let Test = this.state.isLoading
        ? <p>Isloading</p>
        : this.state.people.filter(item => item.name === this.state.name).map(item => (
            <div>
                <p>key:{item.name}</p>
                <div>

                    <p>add:{item.address}</p>
                    <p>bank:{item.bank}</p>
                    <p>bankaccount:{item.bankaccountnumber}</p>
                    <p>baselocation:{item.baselocation}</p>
                    <p>basicpay:{item.basicpay}</p>
                    <p>branch:{item.branch}</p>
                    <p>class:{item.class}</p>
                    <p>confirmpassword:{item.confirmpassword}</p>
                    <p>degree:{item.degree}</p>
                    <p>designation:{item.designation}</p>
                    <p>email:{item.email}</p>
                    <p>mobilenumber:{item.mobilenumber}</p>
                    <p>name:{item.name}</p>
                    <p>password:{item.password}</p>
                    <p>salary:{item.salary}</p>

                </div>
            </div>
        ))
    this.state.search = Test;
    return (
        <div>


            <NativeSelect defaultValue="" name="name" onChange={this.handleChange}>
                <option value="choose">choose</option>
                <option value="Nabanit Koirala">Nabanit Koirala</option>
                <option value="Saroj Kumar">Saroj Kumar</option>

            </NativeSelect>
            <button type="submit" onClick={this.handleSubmit}>Search</button>
            <div>
                {Test}

            </div>
        </div>
    )
}
}

自从获得输出值以来,存储在状态中的数组将被过滤并显示在浏览器中,现在我想将过滤后的数组存储在状态中,所以我现在该怎么做。

javascript reactjs filter maps
3个回答
0
投票

维护filteredPeople的单独状态并在handleChange中对其进行更新。渲染时,只需通过filteredPeople进行映射。

请参见代码段:

this.state = {
        people: [
            {
                address: "Biratnagar",
            ...
            }
        name,
        filteredPeople=[],   
        ...

  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({
        [name]: value,
        filteredPeople: this.state.people.filter(item => item[name] === value)
    })
       ...
let Test = this.state.isLoading
        ? <p>Isloading</p>
        : this.state.filteredPeople.map(item => (
            <div>
                <p>key:
        ... 

}

此外,请确保提供value,即this.state.name<NativeSelect>,因为它是受控字段。

<NativeSelect defaultValue="" name="name" value={this.state.name} onChange={this.handleChange}>
                <option value="choose">choose</option>

0
投票

首先,我认为您在render方法中以错误的方式更新状态:

// No-op
this.state.search = Test; 
// Correct way should be
this.setState({ search: Test });

其次,我认为您没有将呈现的值存储到状态中的想法。您应该将过滤后的数组存储在状态中,然后让render方法执行其工作以将其呈现出来。

const Test = <div>{this.state.people.map(item => <p>{item}</p>)}</div>;

this.setState({ search: Test }); // Don't do this

您想要的可能是:

在您的handleChange事件处理程序中,将过滤后的值更新为状态:

handleChange = (e) => {
    const { name, value } = e.target;
    this.setState(prev => ({
      [name]: value,
      people: prev.people.filter(item => item.name === value),
    }));
}

并且在render方法中,您可以直接将其呈现出来:

render() {
    const { people } = this.state;
    return (
      <div>
        <NativeSelect defaultValue="" name="name" onChange={this.handleChange}>
          <option value="choose">choose</option>
          <option value="Nabanit Koirala">Nabanit Koirala</option>
          <option value="Saroj Kumar">Saroj Kumar</option>
        </NativeSelect>

        <button type="submit" onClick={this.handleSubmit}>Search</button>
        <div>
          {
            people.map(item => (
              <div key={item.name}>
                <p>key:{item.name}</p>
                <div>
                  <p>add:{item.address}</p>
                  <p>bank:{item.bank}</p>
                  <p>bankaccount:{item.bankaccountnumber}</p>
                  <p>baselocation:{item.baselocation}</p>
                  <p>basicpay:{item.basicpay}</p>
                  <p>branch:{item.branch}</p>
                  <p>class:{item.class}</p>
                  <p>confirmpassword:{item.confirmpassword}</p>
                  <p>degree:{item.degree}</p>
                  <p>designation:{item.designation}</p>
                  <p>email:{item.email}</p>
                  <p>mobilenumber:{item.mobilenumber}</p>
                  <p>name:{item.name}</p>
                  <p>password:{item.password}</p>
                  <p>salary:{item.salary}</p>
                </div>
              </div>
            ))
          }
        </div>
      </div>
    );
  }
}

Edit fragrant-glitter-xrw7o

提示:如果要比较名称,则可以考虑将它们以小写字母进行比较。除非您想完全相同。

this.setState(prev => ({
  [name]: value,
  people: prev.people.filter(item => item.name.toLowerCase() === value.toLowerCase())
}));

0
投票

您可以只修改handleChange()

handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({
        [name]: value
    })
      var searchedResult=  this.state.people.filter(item => item.name === this.state.name);

       this.setState({
        search: searchedResult
       })
       console.log('searched data =>',this.state.search);
}
© www.soinside.com 2019 - 2024. All rights reserved.