我正在学习反应,我有奇怪的情况,理论上很简单,但我不知道如何解决。首先,我使用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()
获得响应,它返回一个dicts数组,并在AddCards
函数中使用它。我犯了很多错误,为了避免它,我使用了函数makeRequest
,它调用axiosCall
,调用AddCards
作为回调(也许有人知道更好的解决方案,因为我认为这个解决方案很糟糕)。但是好的,现在我正在尝试使它工作,我创建了状态,所以在它改变时,react应该重新呈现,默认情况下我使它为null。if (cards[0])
检查响应是否出现,并且它应该改变状态。但是我有一个错误Unhandled Rejection (Error): Invalid hook call
。我该怎么办才能解决这个问题?
发布于 2020-03-13 06:09:39
要么将请求响应作为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'));
});
https://stackoverflow.com/questions/60671819
复制相似问题