[英]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.起初我使用
props.children
并且我想在收到响应时呈现代码的某些部分。 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.我想要做的是从
axiosCall()
获取响应,它返回一个axiosCall()
数组并在AddCards
函数中使用它。 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).我有很多的错误,避免它,我使用的功能
makeRequest
它调用axiosCall
它调用AddCards
作为回调(也许有人知道更好的解决办法,因为这是一个可怕的,我认为)。 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. if (cards[0])
检查响应是否到来,它应该改变状态。 But I have an error Unhandled Rejection (Error): Invalid hook call
.但是我有一个错误
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:您要么将请求响应作为
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'));
});
Or you use the useEffect
hook:或者你使用
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.