简体   繁体   中英

React, delay render and hooks

I'm learning react and I have weird situation, it's simple in theory but I don't know how to solve it. At first I'm using props.children and I want to render some part of the code when I get the response. I'm kind of solve it in a strange way but I still have errors. So have a look:

function AddCards(axiosResponse) {

  const [cardsCode, setCardsCode] = React.useState(null);

  const handleGetCards = (newCode) => {
    setCardsCode(newCode);
  };

  var firstText = null;
  var cards = axiosResponse;
  if (cards[0]) {
    firstText = [];
    firstText.push( <div>
      <h1>{cards[0].title}</h1>
      <p>{cards[0].text}</p></div>
    );
    handleGetCards(firstText);
  }

  return (
    <ButtonAppBar>
      {cardsCode}
    </ButtonAppBar>
  );
}

function makeRequest() {
  axiosCall(AddCards);
}

makeRequest();

ReactDOM.render(<AddCards />, document.querySelector('#root'));

The thing I wanted to do is to get the response from axiosCall() which returns an array of dicts and use it in the AddCards function. I had a lot of errors and to avoid it I used function makeRequest which calls axiosCall which calls AddCards as a callback (maybe someone knows better solution because that one is horrible I think). But ok, now I'm trying to make it work, I created state so react should re-render when it changed and I made it null by default. And if (cards[0]) checks if response came and it should change the state. But I have an error Unhandled Rejection (Error): Invalid hook call . What should I do to solve it?

Either you pass the request response as a prop to your component:

function AddCards(props) {
  const response = props.response;
  // do stuff with data here
}

function makeRequest() {
  // some further logic here
  axiosCall();
}

makeRequest().then((response) => {
  ReactDOM.render(<AddCards response={response}/>, document.querySelector('#root'));
});

Or you use the useEffect hook:

import React, { useEffect } from 'react';

function AddCards() {
  const [cardsCode, setCardsCode] = React.useState(null);

  useEffect(() => {
    makeRequest().then((response) => {
      // extract data from response based on your need
      setCardsCode(response);
    });
  }, []);

  // access cardsCode in your function
}


makeRequest().then((response) => {
  ReactDOM.render(<AddCards/>, document.querySelector('#root'));
});

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