我正在构建一个应用程序,在应用程序的开始有一个API调用,其中包含应用程序的所有数据。然后,我使用React Navigation路由到主屏幕(和其他屏幕)。我试图将API调用中的数据传递到主屏幕,但我没有在Home元素中接收到这些数据。
代码是这样的。
App. js
export default function App() {
const [responseJson, setResponseJson] = useState([])
async function fetchData() {
await fetch('http://api.xxx.com/')
.then(response => response.json())
.then(responseJson => {
setResponseJson(responseJson);
})
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" response={responseJson} component={Home} options={{headerShown:false}}/>
</Stack.Navigator>
</NavigationContainer>
);
主屏幕.js
export const Home = (props) => {
return(
<View style={styles.container}>
{console.log(props)}
</View>
)
}
console.log给我提供了一个 Object
与 navigation
和 route
钥匙,但没有 response
键。我如何将数据传递到主屏幕?
你可以使用React的useEffect钩子。但我不确定你是否通过这种方式将它们传递给Stack.Screen来获得它们。我认为应该是这样的。
<Stack.Screen name="Home" component={props => <Home {...props} response={responseJson}/>} options={{headerShown:false}}/>
钩子示例。
React.useEffect(() => {
async function fetchData() {
await fetch('http://api.xxx.com/')
.then(response => response.json())
.then(responseJson => {
setResponseJson(responseJson);
})
}
fetchData()
// cleanup function if needed, on unmount
// return () => doSomeCleanUp()
},[])