在React Navigation中向Stack.Screen传递Fetch API响应。

问题描述 投票:0回答:1

我正在构建一个应用程序,在应用程序的开始有一个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给我提供了一个 Objectnavigationroute 钥匙,但没有 response 键。我如何将数据传递到主屏幕?

reactjs react-native react-navigation
1个回答
0
投票

你可以使用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()
},[])
© www.soinside.com 2019 - 2024. All rights reserved.