简体   繁体   English

如何在 reactjs 中的 state 中设置数据

[英]How can i set data in state in reactjs

Since i am new in react,i used filter and map to select array from array list.I got my output as expected.Now i want to set this.state.search by rendered value.How can i do it? Since i am new in react,i used filter and map to select array from array list.I got my output as expected.Now i want to set this.state.search by rendered value.How can i do it? Here are the pictures of my code below:下面是我的代码图片:

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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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>
    )
}
}

Since i get the output value,the array stored in state is filtered and displayed in the browser,now i want to store the filtered array in state,so how can i do it now.由于我得到了 output 值,存储在 state 中的数组被过滤并显示在浏览器中,现在我想将过滤后的数组存储在 state 中,所以我现在该怎么做。

Maintain a separate state for filteredPeople and update it in your handleChange .filteredPeople的人维护一个单独的 state 并在您的handleChange中更新它。 While rendering, just map through filteredPeople .渲染时,只需 map 通过filteredPeople人。

See the snippet:见片段:

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:
        ... 

}

Also, make sure to provide a value ie this.state.name to <NativeSelect> as it is a controlled field.此外,请确保向<NativeSelect>提供一个value ,即this.state.name ,因为它是一个受控字段。

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

Firstly, I think you're updating the state in the wrong way in your render method:首先,我认为您在render方法中以错误的方式更新了 state:

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

Secondly, I think your idea of storing the rendered node into the state isn't the way to go.其次,我认为您将渲染节点存储到 state 的想法不是 go 的方法。 You should probably store the filtered array result in the state, and then let the render method do its job to render the result out.您可能应该将过滤后的数组结果存储在 state 中,然后让render方法完成其工作以渲染结果。

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

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

What you want is maybe:你想要的可能是:

Add a new array in your state to store the result (instead of calling search maybe good to rename it to result ).在 state 中添加一个新数组来存储结果(而不是调用search可能更好地将其重命名为result )。 This is so that you can keep the original people state to use later for filtering:这样你就可以保留原来的people state 以供以后用于过滤:

constructor() {
    super();
    this.state = {
      people: SAMPLE_DATA,
      name: "", // Maybe you don't need to store this?
      result: []
    };
}

in your handleChange event handler, update the filtered value into the state:在您的handleChange事件处理程序中,将过滤后的值更新为 state:

handleChange = (e) => {
    const { name, value } = e.target;

    this.setState(prev => ({
      [name]: value,
      // You got the value now, so update the result at the same time
      result: prev.people.filter(item => item.name === value),
    }));
}

And in your render method, you can render it out directly:在你的render方法中,你可以直接渲染出来:

render() {
    const { result } = 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>
          {
            result.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>
    );
  }
}

编辑 fragrant-glitter-xrw7o

Tips: if you want to compare names, maybe consider comparing them in lowercase.提示:如果要比较名称,可以考虑以小写形式进行比较。 Unless you want to compare exactly the same.除非你想比较完全相同。

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

You Can just Modify the handleChange()你可以只修改 handleChange()

And remove this line this.state.search = Test from your code because updating state in a render() is not a right way.并从您的代码中删除这一行this.state.search = Test因为在 render() 中更新 state 不是正确的方法。

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);
}



✅Final result ✅最终结果

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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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: "nabanitkoirala@gmail.com",

                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
        })
          var searchedResult=  this.state.people.filter(item => item.name === this.state.name);

           this.setState({
            search: searchedResult
           })
           console.log('searched data =>',this.state.search);
    }
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;// Do not do like this
    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>
    )
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM