【问题标题】:change object into array present another component in react将对象更改为数组在反应中呈现另一个组件
【发布时间】:2021-06-03 19:43:54
【问题描述】:

对于这个非常基本的问题,我很抱歉,因为我是刚接触 js 的新手。我在一个反应​​组件中创建了一个数组,并通过一个组件中的映射函数呈现它,我想根据_id从另一个组件更改(添加/主题)数组。以下是一个示例,可以帮助您更好地理解我真正想要的。在此先感谢先生

    {*Array Component*}
const ArrayData =[
    {
        _id:1,
        title:"All Searches"
    },
    {
        _id:5,
        title:1
    },
    {
        _id:6,
        title:"4"
    }
]
export default ArrayData;

{*2nd Component*}

import react from "react"
import ArrayData from ArrayComponent
class Parent extends React.Component {
    constructor() {
        super();
        this.state = {
            ArrayData:ArrayData,
            collapsed: false,
        }
}
render() {
        const { ArrayData } = this.state;
        return (
            <>
               <FirstChild Data={ArrayData} />
               <SecondChild />
            </>
        );
    }
}

export default Parent;
!------------------------------------------!

{*FirstChild*}

class FirstChild extends React.Component {
    constructor(props){
        super();
        this.state={
            ArrayData:props.ArrayData
        }
    }
    render() {
        const { ArrayData} = this.state;
        const renderArray = ArrayData.slice(0, 5).map(Object => {
            return <h1>{object._id} </h1>
        })
        return (
            <>
              {renderArray}
            </>
        );

    }
}

export default FirstChild;


!-----------------------------------------!

{*SecondChild*}

import { React } from "react";
const SecondChild = () => {

    const handleUpdate=(_id, Title) =>{

        {*function that can add the inputs as a object into that arrayComponent*}

    }
    const handleDelete=(_id) =>{

        {*function that can delete a object from that arrayComponent having the id given by User in the feild*}

    }

    return (
        <>
                    <input type='text' name='_id' placeHolder="Which object you want to delete" />
                    <button type=Submit onClick={handleDelete} >Delete</button>
                    <br></br>
                    <input type='text' name='_id' />
                    <input type='text' name='title' />
                    <button type=Submit onClick={handleUpdate} >Update</button>
        </>
    );
}

export default SecondChild;

【问题讨论】:

  • change是什么意思,你想对ArrayData数组进行CRUD操作吗。
  • 主题到底是什么?它们是 ArrayData 内部的对象吗?
  • 您尚未从Parent 组件传递tabsData。那么你怎么能进入child 组件呢?请具体说明您想做什么以及您尝试过什么。
  • 抱歉弄错了
  • 我需要在需要时将新项目添加到我的数组中,并从同一个数组中删除包含特定 id 的项目,例如如果用户添加数据,它应该将该数据作为另一个对象添加到该数组中( 3 之前和现在该数组中的 4 个对象)并且用户想要删除具有特定 id 的项目然后它从具有该 id 的数组中删除该对象

标签: javascript arrays reactjs jsx


【解决方案1】:

CODESANDBOX

您需要做的就是在Parent 组件上声明handleDeletehandleUpdate,并将其作为props 传递到SecondChild 组件中。如果我们将state及其methods放在Parent组件中,那么它就很容易跟踪、调试和维护。如果我们定义另一个组件,比如ThirdComponent,传递方法会很容易,它还包含对ArrayData 数组执行CRUD 操作的功能。

FirstChild 组件中,您正在解构 ArrayData const { ArrayData} = this.state; 并在渲染方法中使用它。它不会更新我们收到新的props,因为您正在渲染一次创建的数组状态(因为构造函数将被调用一次)并且我们想要来自父组件的ArrayData 的最新值。我们可以直接在render方法中使用props。您需要查看 react lifecycle 方法。

Parent.js

import React from "react";
import ArrayData from "./ArrayComponent";
import FirstChild from "./FirstChild";
import SecondChild from "./SecondChild";

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      ArrayData: ArrayData,
      collapsed: false
    };

    this.handleDelete = this.handleDelete.bind(this);
    this.handleUpdate = this.handleUpdate.bind(this);
  }

  handleDelete(id) {
    const idToDelete = parseInt(id, 10);

    this.setState((state) => {
      const filteredArrayData = state.ArrayData.filter(
        (el) => el._id !== idToDelete
      );
      return {
        ArrayData: filteredArrayData
      };
    });
  }

  handleUpdate(newObj) {
    console.log(newObj);
    this.setState((state) => ({
      ArrayData: [...state.ArrayData, newObj]
    }));
  }

  render() {
    return (
      <>
        <FirstChild Data={this.state.ArrayData} />
        <SecondChild
          handleUpdate={this.handleUpdate}
          handleDelete={this.handleDelete}
        />
      </>
    );
  }
}

export default Parent;

FirstChild.js

import React from "react";

class FirstChild extends React.Component {
  render() {
    return (
      <>
        {this.props.Data.slice(0, 5).map((el) => {
          return <h1 key={el._id}>{el._id}</h1>;
        })}
      </>
    );
  }
}

export default FirstChild;

SecondChild.js

import React, { useState } from "react";
const SecondChild = ({ handleUpdate, handleDelete }) => {
  const [idToDelete, setIdToDelete] = useState(null);
  const [newID, setNewID] = useState(null);
  const [newTitle, setNewTitle] = useState("");

  return (
    <>
      <input
        name="_id"
        type="number"
        onChange={(e) => setIdToDelete(e.target.value)}
        placeholder="Which object you want to delete"
      />
      <button type="submit" onClick={() => handleDelete(idToDelete)}>
        Delete
      </button>

      <br></br>
      <br></br>
      <br></br>

      <input
        type="text"
        name="_id"
        placeholder="id"
        onChange={(e) => setNewID(e.target.value)}
      />

      <input
        type="text"
        name="title"
        placeholder="title"
        onChange={(e) => setNewTitle(e.target.value)}
      />
      <button
        type="submit"
        onClick={() => handleUpdate({ _id: newID, title: newTitle })}
      >
        Update
      </button>
    </>
  );
};

export default SecondChild;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2018-04-25
    • 2018-11-11
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多