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

huangapple go评论165阅读模式
英文:

Pass a variable from one file to another in React Native

问题

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

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

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

英文:

I'm building a front end app on React Native. One file (screen) is generating a Token using the following code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

In another file I must use that token for verification

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

fetch(&#39;http://192.168.1.11:8080/api/books&#39;, {
  method: &#39;POST&#39;,
  headers: {
    Accept: &#39;application/json&#39;,
    &#39;Content-Type&#39;: &#39;application/json&#39;,
    &#39;Authorization&#39;: &#39;Bearer &#39; + JwToken

  },
  body: JSON.stringify({
    title: &#39;new book&#39;,
    price: 4
  })
});

<!-- end snippet -->

I had no idea how to pass the token between the two files.

答案1

得分: 1

这是我以前从React Navigation 文档中引用过的内容,似乎符合您的需求。

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => {
          /* 1. 使用参数导航到 Details 路线 */
          navigation.navigate('Details', {
            itemId: 86,
            otherParam: '你想要的任何内容',
          });
        }}
      />
    </View>
  );
}

function DetailsScreen({ route, navigation }) {
  /* 2. 获取参数 */
  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="再次前往详情页"
        onPress={() =>
          navigation.push('Details', {
            itemId: Math.floor(Math.random() * 100),
          })
        }
      />
      <Button title="前往首页" onPress={() => navigation.navigate('Home')} />
      <Button title="返回" onPress={() => navigation.goBack()} />
    </View>
  );
}
英文:

This is something I've referenced before from the React Navigation Docs that seems to fit your needs.

function HomeScreen({ navigation }) {
return (
&lt;View style={{ flex: 1, alignItems: &#39;center&#39;, justifyContent: &#39;center&#39; }}&gt;
&lt;Text&gt;Home Screen&lt;/Text&gt;
&lt;Button
title=&quot;Go to Details&quot;
onPress={() =&gt; {
/* 1. Navigate to the Details route with params */
navigation.navigate(&#39;Details&#39;, {
itemId: 86,
otherParam: &#39;anything you want here&#39;,
});
}}
/&gt;
&lt;/View&gt;
);
}
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId } = route.params;
const { otherParam } = route.params;
return (
&lt;View style={{ flex: 1, alignItems: &#39;center&#39;, justifyContent: &#39;center&#39; }}&gt;
&lt;Text&gt;Details Screen&lt;/Text&gt;
&lt;Text&gt;itemId: {JSON.stringify(itemId)}&lt;/Text&gt;
&lt;Text&gt;otherParam: {JSON.stringify(otherParam)}&lt;/Text&gt;
&lt;Button
title=&quot;Go to Details... again&quot;
onPress={() =&gt;
navigation.push(&#39;Details&#39;, {
itemId: Math.floor(Math.random() * 100),
})
}
/&gt;
&lt;Button title=&quot;Go to Home&quot; onPress={() =&gt; navigation.navigate(&#39;Home&#39;)} /&gt;
&lt;Button title=&quot;Go back&quot; onPress={() =&gt; navigation.goBack()} /&gt;
&lt;/View&gt;
);
}

huangapple
  • 本文由 发表于 2020年8月23日 02:58:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63540011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定