我正在学习 React,我遇到了奇怪的情况,理论上很简单,但我不知道如何解决。首先,我使用 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() 获取响应,该响应返回一个字典数组,并在 AddCards 函数中使用它。我遇到了很多错误,为了避免它,我使用了函数 makeRequest
,它调用 axiosCall
,它调用 AddCards
作为回调(也许有人知道更好的解决方案因为我认为那个太可怕了)。但是好吧,现在我正在尝试让它工作,我创建了状态,所以 react 应该在它改变时重新渲染,并且我默认将其设置为空。 if (cards[0])
检查响应是否到来并且它应该改变状态。但我有一个错误未处理的拒绝(错误):无效的 Hook 调用
。我应该怎么解决?
最佳答案
将请求响应作为 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
钩子(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'));
});
关于javascript - React、延迟渲染和钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60671819/