我有以下代码:
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;
我试图调用 setArticles 导致重新渲染过多。 React 限制渲染次数以防止无限循环
此错误位于: 在应用程序中(由 ExpoRoot 创建) 在 ExpoRoot(在 renderApplication.js:45) 在 RCTView 中(在 View.js:34) 在视图中(在 AppContainer.js:106) 在 RCTView 中(在 View.js:34) 在视图中(在 AppContainer.js:132) 在 AppContainer 中(在 renderApplication.js:39) ...
答案 0 :(得分:2)
你应该将初始化移动到 useState
钩子,你触发 inifite rerender
const App = () => {
// GOOD, initialize once
const [articles, setArticles] = useState([{"flight_number":110," ...]);
// BAD, rerender loop
setArticles([{"flight_number":110," ...]);
...
}
答案 1 :(得分:0)
以下是工作代码。对 fetch 方法和 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;