[英]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.