在react native中将变量从一个文件传递到另一个文件

5jdjgkvh  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(300)

我正在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
  })
});

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

nzrxty8p

nzrxty8p1#

这是我以前从react导航文档中引用过的,似乎符合您的需要。

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>
  );
}

相关问题