簡體   English   中英

如何將輸入值作為標簽添加到對象數組並在反應js中顯示

[英]How to add input value as a tag to an object array and display it in react js

如何向對象數組添加鍵值? 我正在獲取一個 api,並希望從用戶的輸入中為特定的學生/人員數組添加值。 假設我們點擊第一個列表的輸入並輸入 xyz,它應該添加一個標簽:'xyz',然后如果我們添加 abc,那么它必須是標簽:['xyz','abc']。我是新手如果出現嚴重錯誤,請做出反應,請原諒我。

import React from "react";
import "./App.css";
export default class FetchRandomUser extends React.Component {


  state = {
    loading: true,
    people: [],
    input: '',
  }

  async componentDidMount() {
    const url = "https://api.hatchways.io/assessment/students";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ people: data.students, loading: false });
    //
  }

  onChangeHandler(e) {
    this.setState({
      input: e.target.value,
    })
  }

  render() {
    if (this.state.loadin) {
      return <div>loading...</div>;
    }

    if (!this.state.people.length) {
      return <div>didnt get person...</div>;
    }

    const list = this.state.people.filter(person => this.state.input.toLowerCase() === '' || person.firstName.toLowerCase().includes(this.state.input.toLowerCase()) || person.lastName.toLowerCase().includes(this.state.input.toLowerCase()))
    .map(person => (
      <div key={person.id}>
        <li>
          {JSON.stringify(person.firstName)}
          {JSON.stringify(person.lastName)}
          {/*want to add newTag value for particular person in list */}
          <input type="text" />
          {/* and display it here */}
        </li>
      </div>
    ));

    return (
      <div>
        <div className="example1">
          {/* this input will search and filter person based on first and last name */}
          <input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)} />
          <ul>{list}</ul>
        </div>
      </div>
    )
  }
}

如果我正確理解您的問題,這是您可以向對象添加鍵值的方法之一:

var obj ={ a: 1, b: 2 };
obj.c = 5  
console.log(obj);
output  
Object { a: 1, b: 2, c: 5 }

由於您想為特定學生執行此操作,因此應該有一個邏輯來首先找到正確的學生。 所以你必須遍歷你的學生數組。

const data = [your array]
const updatedData = data.map(student =>{
if (student.id === person.id) {// you need to use the correct key names here
student = {... student,
 tag: "xyz" // this xyz comes from you input, you need to adjust here
}
}
return student
})

之后,您可以呈現正確的數據。 請記住,我只是寫了一次如何更新數組。 由於您使用的是 react,因此您需要應用此邏輯來更新您的狀態。 所以每次有更新時,狀態也應該更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM