You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何在两个.js文件间调用并使用变量?

React Native 组件间传递数据的解决方案

当前代码的问题

  • firstPage.js 中的 data 是组件内部的 useState 状态,属于组件私有变量,无法通过 import 直接导出使用
  • 导入时命名错误:firstPage.js 导出的是 TestOne 组件,而非 pageOne,且没有对外导出 data 变量
  • TestOne 组件没有返回有效UI,仅返回空的 React.Fragment,无法实现页面跳转或嵌套子组件的逻辑

方案一:页面跳转时通过导航参数传递(适合页面间跳转场景)

如果你的两个页面是通过 React Navigation 进行路由管理,可以在跳转时将数据作为参数传递:

修改 firstPage.js

import React, { useEffect, useState } from "react";
import { View, Text, Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

const TestOne = () => {
  const [data, setData] = useState(null);
  const navigation = useNavigation();

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/5")
      .then((response) => response.json())
      .then((data) => setData(data))
      .catch((error) => console.error(error));
  }, []);

  if (!data) {
    return <View><Text>Loading...</Text></View>;
  }

  return (
    <View>
      <Text>首页数据:{data.title}</Text>
      <Button 
        title="跳转到第二页"
        onPress={() => navigation.navigate('TrailTwo', { postData: data })}
      />
    </View>
  );
};
export default TestOne;

修改 secondPage.js

import React from 'react'; 
import { View, Text } from 'react-native';

const TrailTwo = ({ route }) => {
  // 从路由参数中获取传递的数据
  const { postData } = route.params;

  return (
    <View>
      <Text>第二页数据:</Text>
      <Text>标题:{postData.title}</Text>
      <Text>内容:{postData.body}</Text>
    </View>
  );
};
export default TrailTwo;

方案二:抽离数据请求逻辑,在多个页面复用

如果两个页面只是需要获取同一份数据,不需要在页面间传递,可以把请求逻辑抽成独立工具函数:

创建 api.js

// 封装数据请求函数
export const fetchPost = async () => {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/5");
    return await response.json();
  } catch (error) {
    console.error(error);
    throw error;
  }
};

在 firstPage.js 中使用

import React, { useEffect, useState } from "react";
import { View, Text } from 'react-native';
import { fetchPost } from './api';

const TestOne = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const getPost = async () => {
      const post = await fetchPost();
      setData(post);
    };
    getPost();
  }, []);

  if (!data) {
    return <View><Text>Loading...</Text></View>;
  }

  return (
    <View>
      <Text>首页数据:{data.title}</Text>
    </View>
  );
};
export default TestOne;

在 secondPage.js 中使用

import React, { useEffect, useState } from 'react'; 
import { View, Text } from 'react-native';
import { fetchPost } from './api';

const TrailTwo = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const getPost = async () => {
      const post = await fetchPost();
      setData(post);
    };
    getPost();
  }, []);

  if (!data) {
    return <View><Text>Loading...</Text></View>;
  }

  return (
    <View>
      <Text>第二页数据:</Text>
      <Text>标题:{data.title}</Text>
      <Text>内容:{data.body}</Text>
    </View>
  );
};
export default TrailTwo;

方案三:使用 Context 全局共享数据(适合多组件共享数据场景)

如果你的应用中有多个组件需要使用这份数据,可以用 React Context 实现全局状态管理:

创建 PostContext.js

import React, { createContext, useContext, useEffect, useState } from 'react';

const PostContext = createContext();

// 全局状态提供者
export const PostProvider = ({ children }) => {
  const [postData, setPostData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/5")
      .then((response) => response.json())
      .then((data) => setPostData(data))
      .catch((error) => console.error(error));
  }, []);

  return (
    <PostContext.Provider value={{ postData }}>
      {children}
    </PostContext.Provider>
  );
};

// 自定义 Hook,方便组件获取数据
export const usePost = () => useContext(PostContext);

在 App.js 中包裹全局提供者

import { PostProvider } from './PostContext';
import { NavigationContainer } from '@react-navigation/native';
import TestOne from './firstPage';
import TrailTwo from './secondPage';
// 导入你的导航栈配置

function App() {
  return (
    <PostProvider>
      <NavigationContainer>
        {/* 配置你的导航栈,例如 StackNavigator */}
      </NavigationContainer>
    </PostProvider>
  );
}

export default App;

在 firstPage.js 中使用

import React from "react";
import { View, Text } from 'react-native';
import { usePost } from './PostContext';

const TestOne = () => {
  const { postData } = usePost();

  if (!postData) {
    return <View><Text>Loading...</Text></View>;
  }

  return (
    <View>
      <Text>首页数据:{postData.title}</Text>
    </View>
  );
};
export default TestOne;

在 secondPage.js 中使用

import React from 'react'; 
import { View, Text } from 'react-native';
import { usePost } from './PostContext';

const TrailTwo = () => {
  const { postData } = usePost();

  if (!postData) {
    return <View><Text>Loading...</Text></View>;
  }

  return (
    <View>
      <Text>第二页数据:</Text>
      <Text>标题:{postData.title}</Text>
      <Text>内容:{postData.body}</Text>
    </View>
  );
};
export default TrailTwo;

方案选择建议

  • 仅页面跳转传递数据:优先用导航参数传递
  • 多个页面独立获取同一份数据:用抽离请求函数的方式
  • 多个组件(跨层级、跨页面)需要共享数据:用Context 全局状态管理

内容的提问来源于stack exchange,提问作者My Medi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:55:20