我的应用程序有一个页面可以从API提取和显示数据,DrawerItem
会将用户定向到该页面。在此页面中,有三个按钮,每个按钮在单击时都会从API提取不同的数据,默认情况下,每次将用户定向到此页面时,都会单击第一个按钮。单击其他按钮后,屏幕上的数据将被清除并再次获取。
在此ShowDataScreen.js
const ShowDataScreen = props => {
const [records, setRecords] = useState([]);
// call this every time when this screen is focused
useFocusEffect(
React.useCallback(()=>{
const fetchData = async(type) => {...fetch data and setRecords};
fetchData('1'); // get type 1 data
})
)
// call this when buttons are clicked
const fetchData = async(type) => {
if(type=='1'){ setTypeOneSelected(true); //set other false }
if(type=='2'){ setTypeTwoSelected(true); //set other false }
if(type=='3'){ setTypeThreeSelected(true); //set other false }
// get data from api and update the screen by setRecords
setRecords(result)
}
return(
<View>
<TouchableOpacity style={typeOneSelected?styles.selected: styles.notSelected} title="datatype1" onPress={fetchData('1')}> 1 </TouchableOpacity>
<TouchableOpacity style={typeTwoSelected?styles.selected: styles.notSelected} title="datatype2" onPress={fetchData('2')}> 2 </TouchableOpacity>
<TouchableOpacity style={typeThreeSelected?styles.selected: styles.notSelected} title="datatype3" onPress={fetchData('3')}> 3 </TouchableOpacity>
<FlatList data={records}>
// fetched data shown here
</FlatList>
</View>
)
}
每次用户访问此页面时,都应该看到类型1的数据和样式。如果单击其他按钮应相应地更新屏幕。如何正确更新数据和样式?
答案 0 :(得分:0)
根据您的评论,它可能是useeffect挂钩持续运行的原因。您可以检查此示例的工作版本。我已经使用通用API嘲笑了异步调用。这可以根据要求工作。
function ProfileScreen() {
const [records, setRecords] = React.useState('');
const [type, setType] = React.useState(1);
useFocusEffect(
React.useCallback(() => {
console.log('Screen was focused');
fetchData(1);
}, [])
);
const fetchData = async (type) => {
console.log(type);
const data = await fetch('https://jsonplaceholder.typicode.com/todos/' + type);
const json = await data.json();
setRecords(json);
setType(type);
};
return (
<View>
<TouchableOpacity
style={type === 1 ? styles.selected : styles.notSelected}
title="datatype1"
onPress={() => fetchData(1)}>
<Text>1</Text>
</TouchableOpacity>
<TouchableOpacity
style={type === 2 ? styles.selected : styles.notSelected}
title="datatype2"
onPress={() => fetchData(2)}>
<Text>2</Text>
</TouchableOpacity>
<TouchableOpacity
style={type === 3 ? styles.selected : styles.notSelected}
title="datatype3"
onPress={() => fetchData(3)}>
<Text>3</Text>
</TouchableOpacity>
<Text>{JSON.stringify(records)}</Text>
<Text>{type}</Text>
</View>
);
}