React Native中未显示组件阵列



我是React Native的新手,我想知道为什么我的代码不能工作。我通过console.log知道我的输出数组中充满了正确的数据,但由于某种原因,当我试图写出输出时,它似乎没有向移动屏幕写入任何内容。我想知道为什么会这样。

const ChampionScreen = () => {
const [champions, setChampions] = useState([]);
var output = [];
useEffect(() => {
AxiosService.getChampions()
.then(data => {
setChampions(data);
var champarr =[];
Object.keys(champions).forEach(function(key){
champarr.push(champions[key]);
}) 
for(let i = 0; i < champarr.length;i++){
let champion = JSON.parse(JSON.stringify(champarr[i]));
var tempItem = (
<View key={i}>
<Text>{champion.name}</Text>
</View>
);
output[i] = (tempItem);
}
}).catch(err => console.error(err))
},[])
return (
<ScrollView>
<View>
{output}
</View>
</ScrollView>
)
}

您没有将output定义为状态变量,它也不会以这种方式触发渲染。之后,当你用Object.keys方法映射data对象时,你有点运气,因为状态更新是异步的,所以你不应该设置状态并立即使用状态,使用你已经获取的数据。在这里:

const ChampionScreen = () => {
const [champions, setChampions] = useState([]);
const [output, setOutput] = useState([]);
useEffect(() => {
AxiosService.getChampions()
.then(data => {
setChampions(data);
var champarr = [];
let axiosOutput = [];
Object.keys(data).forEach(function(key){
champarr.push(data[key]);
}) 
for(let i = 0; i < champarr.length;i++){
let champion = JSON.parse(JSON.stringify(champarr[i]));
var tempItem = (
<View key={i}>
<Text>{champion.name}</Text>
</View>
);
axiosOutput.push(tempItem);
}
setOutput(axiosOutput)
}).catch(err => console.error(err))
},[])
return (
<ScrollView>
<View>
{output}
</View>
</ScrollView>
)
}

最新更新