简体   繁体   中英

Dynamic page changing based on button click - React

Just to frame my issue, I'm building a react application for the first time and having some issues. I have a functional react component that's calling and showing another functional component two times, with slight differences due to the key prop. These two components are a register and login form made using bootstrap. I am sending the data from the login form to an API. This part of the code is working. My issue is in dynamically changing the page after submitting. I want to be able to click the login button and be sent to a new page without the login and register forms visible. I am trying to pass a function to these components that changes the state of the calling function and check in the parent function what to show based on this. The code that shows my attempts is here: This is the hook in the main component that I am changing.

 const [keyID, setKey] = useState(true);

[EDIT] This function is called in the main functional component like this <Home KeyID={keyID} keyChanger={setKey} /> :

 function Home(KeyID, setKey) {
 if (KeyID) {
   return (
     <>
       <RegLogForm KeyID={1} setKey={setKey} />
       <RegLogForm KeyID={2} setKey={setKey} />
     </>
   );
 } else {
   return (
     <>
     <LoggedIn />
     </>
   )
 }
}

And this being in the called component:

<Form
  onSubmit={event => {
    event.preventDefault();
    let name2 = encodeURIComponent(name);
    ChangePage(APIHitter(props.UserID, name2, password));
    props.setKey(false);
  }}
>

I have also tried passing this into the form component aswell:

  const increment = () => {
    setKey(keyID => false);
  };

I would love to be shown the right direction to go with this. The error I am getting with this is props.setKey is not a function .

Since Home is being rendered like this -

<Home KeyID={keyID} keyChanger={setKey} />

The function should accept the props parameter with named props this way -

function Home({KeyID, keyChanger: setKey}) {

Which is equivalent to the old syntax -

function Home(props) {
  var KeyID = props.KeyID;
  var setKey = props.keyChanger;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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