[英]React, delay render and hooks
我正在學習反應,我遇到了奇怪的情況,理論上很簡單,但我不知道如何解決。 起初我使用props.children
並且我想在收到響應時呈現代碼的某些部分。 我有點以一種奇怪的方式解決它,但我仍然有錯誤。 所以看看:
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'));
我想要做的是從axiosCall()
獲取響應,它返回一個axiosCall()
數組並在AddCards
函數中使用它。 我有很多的錯誤,避免它,我使用的功能makeRequest
它調用axiosCall
它調用AddCards
作為回調(也許有人知道更好的解決辦法,因為這是一個可怕的,我認為)。 但是好的,現在我正在嘗試使其工作,我創建了狀態,因此當它發生變化時應該重新渲染並且我默認將其設為空。 if (cards[0])
檢查響應是否到來,它應該改變狀態。 但是我有一個錯誤Unhandled Rejection (Error): Invalid hook call
。 我應該怎么做才能解決它?
您要么將請求響應作為prop
傳遞給您的組件:
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'));
});
或者你使用useEffect
鈎子:
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'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.