繁体   English   中英

在 React Native 中将变量从一个文件传递到另一个文件

[英]Pass a variable from one file to another in React Native

我正在 React Native 上构建一个前端应用程序。 一个文件(屏幕)正在使用以下代码生成令牌

 fetch("http://192.168.1.11:8080/api/login", { method: 'POST', body: JSON.stringify({ username: 'user' }), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }).then((response) => response.json()).then((json) => { this.setState({ JwToken: json.token }); }).then((json) =>this.props.navigation.navigate('Home')/).catch((error) => console.error(error)).finally(() => { this.setState({ isLoading: false }); });

在另一个文件中,我必须使用该令牌进行验证

 fetch('http://192.168.1.11:8080/api/books', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + JwToken }, body: JSON.stringify({ title: 'new book', price: 4 }) });

我不知道如何在两个文件之间传递令牌。

这是我之前从React Navigation Docs中引用的内容,似乎符合您的需求。

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => {
          /* 1. Navigate to the Details route with params */
          navigation.navigate('Details', {
            itemId: 86,
            otherParam: 'anything you want here',
          });
        }}
      />
    </View>
  );
}

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId } = route.params;
  const { otherParam } = route.params;
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Text>itemId: {JSON.stringify(itemId)}</Text>
      <Text>otherParam: {JSON.stringify(otherParam)}</Text>
      <Button
        title="Go to Details... again"
        onPress={() =>
          navigation.push('Details', {
            itemId: Math.floor(Math.random() * 100),
          })
        }
      />
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM