Home > Net >  useState replaces the current element
useState replaces the current element

Time:07-29

I have 2 buttons. Add1 and Add2

The Add2 button in the Test does not work. What am I doing wrong. I'm not very familiar with React.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);

  useEffect(() => {});

  const Test = observer(() => {
    return (
      <div>
        <p>
          Test -
          <button onClick={() => setComponent([...component, Test])}>
            Add 2
          </button>
        </p>
      </div>
    );
  });

  return (
    <div>
      {component.map((Input, index) => (
        <Input key={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>Add 1</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox: https://codesandbox.io/s/react-hooks-useeffect-forked-ml77pz

CodePudding user response:

You should not create component inside another component if you do not keep its reference!

Move it outside of App and add prop setComponent

const Test = observer(({setComponent}) => {
  return (
    <div>
      <p>
        Test -
        <button onClick={() => setComponent(component => [...component, Test])}>
          Add 2
        </button>
      </p>
    </div>
  );
});

function App() {
   ...
}

Then when you render, pass 'setComponent' to it:

<Input key={index} setComponent={setComponent} />

CodePudding user response:

You have not defined the base case for this recursive render

 const Test = observer(() => {
    return (
      <div>
        <p>
          Test -
          <button onClick={() => setComponent([...component, Test])}>
            Add 2
          </button>
        </p>
      </div>
    );
  });
  • Related