简体   繁体   English

ReactJS同时将函数从父级传递给子级并访问父级状态未完全返回

[英]ReactJS while passing function from parent to child and accessing parent state not returning completely

I was trying to access Parent state when a function is called from Child component, for that created a function in Parent component and passed it to Child, issue is I am not able to access the state completely.当从子组件调用函数时,我试图访问父状态,因为在父组件中创建了一个函数并将其传递给子,问题是我无法完全访问状态。 for example on button click I add a new input field and a delete button, suppose I added 10 input fields, and added all of them in state array, but when i click delete button of second input field, the count I get from state is 1, similar if I click 5th delete button i get count as 4 and it only show me 4 items in state, but it has 10 items Here is an example link https://codesandbox.io/s/add-react-component-onclick-forked-t2i0ll?file=/src/index.js:0-869例如在按钮单击时,我添加了一个新的输入字段和一个删除按钮,假设我添加了 10 个输入字段,并将它们全部添加到状态数组中,但是当我单击第二个输入字段的删除按钮时,我从状态中获得的计数是1,类似,如果我单击第 5 个删除按钮,我得到计数​​为 4,它只显示状态中的 4 个项目,但它有 10 个项目这是一个示例链接https://codesandbox.io/s/add-react-component- onclick-forked-t2i0ll?file=/src/index.js:0-869

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Input = ({ deleteRow, position }) => {
  const handleDelete = () => deleteRow(position);
  return (
    <>
      <input placeholder="Your input here" />
      <button onClick={handleDelete}>Delete</button>
    </>
  );
};

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onDeleteRow = (position) => {
    console.log("inputCount", inputList);
  };
  const onAddBtnClick = (event) => {
    setInputList(
      inputList.concat(
        <Input
          key={inputList.length}
          position={inputList.length}
          deleteRow={onDeleteRow}
        />
      )
    );
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList}
    </div>
  );
};

ReactDOM.render(<Form />, document.getElementById("form"));

It's called a stale closure .这被称为陈旧的闭包

You can avoid that by not storing react elements inside the state.您可以通过不在状态中存储反应元素来避免这种情况。

Example:例子:

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onDeleteRow = (position) => {
    console.log("inputCount", inputList);
  };
  const onAddBtnClick = (event) => {
    setInputList([...inputList, inputList.length])
    );
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList.map(item => (
        <Input
          key={item}
          position={item}
          deleteRow={onDeleteRow}
        />
      )}
    </div>
  );
};

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

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