#javascript #reactjs #react-native
Вопрос:
У меня следующий код:
import { StyleSheet, View, Text } from 'react-native';
import React, { useState, useEffect } from 'react';
const App = () => {
const [articles, setArticles] = useState([]);
const [loading, setLoading ] = useState(false);
setArticles([{"flight_number":110," ...])
useEffect(()=>{
setLoading(true);
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.spacexdata.com/v3/launches/upcoming", requestOptions)
.then(response => response.text())
//.then(setArticles(response => result))
.then(result => console.log(result))
.catch(error => console.log('error', error));
setLoading(false);
} , []);
if (loading){
return <></>
} else {
return <HomeScreen articles = { articles }/>
}
};
const HomeScreen = (props) => {
console.log("articles: ", props.articles);
return (
<View>
{
props.articles.map((article, index)=>{
return <Text key = {index}>
{ article.mission_name }
</Text>
})
}
</View>
);
}
export default App;
Я пытаюсь вызвать набор элементов, вызывающий слишком много повторных рендеров. React ограничивает количество рендеров, чтобы предотвратить бесконечный цикл
Эта ошибка находится по адресу: в приложении (созданном ExpoRoot) в ExpoRoot (в приложении визуализации.js:45) в RCTView (в представлении.js:34) в представлении (в приложении. js:106) в представлении RCTView (в представлении.js:34) в представлении (в приложении. js:132) в приложении (в приложении визуализации.js:39) …
Ответ №1:
Вы должны переместить инициализацию в useState
hook, вы запускаете повторный запуск inifite
const App = () => {
// GOOD, initialize once
const [articles, setArticles] = useState([{"flight_number":110," ...]);
// BAD, rerender loop
setArticles([{"flight_number":110," ...]);
...
}
Комментарии:
1. Прежде всего, спасибо вам за ваш вклад, теперь у меня есть только одна проблема, есть ли способ настроить вывод выборки с помощью setArticles?
Ответ №2:
Ниже приведен рабочий код. Внес некоторые изменения в метод выборки и метод UseSate.
Рендеринг был неправильным setArticles([{"flight_number":110," ...])"
.
And to have the response to be loaded into the View tag, the JSON response needs to be parsed before using it.
import { StyleSheet, View, Text } from 'react-native';
import React, { useState, useEffect } from 'react';
const App = () => {
const [articles, setArticles] = useState([{"flight_number":110}]);
const [loading, setLoading ] = useState(false);
useEffect(()=>{
setLoading(true);
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.spacexdata.com/v3/launches/upcoming", requestOptions)
.then(response => response.text())
//.then(setArticles(response => result))
.then(result =>
setArticles(JSON.parse(result)))
.catch(error => console.log('error', error));
setLoading(false);
} , []);
if (loading){
return <></>
} else {
return <HomeScreen articles = { articles }/>
}
};
const HomeScreen = (props) => {
console.log("articles: ", props.articles.length);
return (
<View>
{
props.articles.map((article, index)=>{
return <Text key = {index}>
{ article.mission_name }
</Text>
})
}
</View>
);
}
export default App;