当前位置:首页 > React

react两个页面之间如何通讯

2026-01-26 04:03:17React

跨页面通信方法

使用URL参数传递数据 在React中可以通过路由的URL参数或查询字符串传递数据。使用react-router-domuseNavigateuseLocation钩子实现。

// 页面A: 传递数据
import { useNavigate } from 'react-router-dom';
function PageA() {
  const navigate = useNavigate();
  const sendData = () => {
    navigate('/pageB?data=example');
  };
  return <button onClick={sendData}>跳转到PageB</button>;
}

// 页面B: 接收数据
import { useLocation } from 'react-router-dom';
function PageB() {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const data = searchParams.get('data');
  return <div>接收到的数据: {data}</div>;
}

使用状态管理库 Redux或Context API可以实现全局状态共享,适合复杂应用场景。

react两个页面之间如何通讯

// 使用Redux示例
// store.js
import { createStore } from 'redux';
const initialState = { sharedData: null };
function reducer(state = initialState, action) {
  switch(action.type) {
    case 'SET_DATA':
      return { ...state, sharedData: action.payload };
    default:
      return state;
  }
}
export const store = createStore(reducer);

// 页面A: 设置数据
import { useDispatch } from 'react-redux';
function PageA() {
  const dispatch = useDispatch();
  const sendData = () => {
    dispatch({ type: 'SET_DATA', payload: 'example' });
  };
  return <button onClick={sendData}>设置共享数据</button>;
}

// 页面B: 获取数据
import { useSelector } from 'react-redux';
function PageB() {
  const sharedData = useSelector(state => state.sharedData);
  return <div>共享数据: {sharedData}</div>;
}

使用浏览器存储 localStorage或sessionStorage适合需要持久化或临时存储的场景。

react两个页面之间如何通讯

// 页面A: 存储数据
function PageA() {
  const storeData = () => {
    localStorage.setItem('sharedData', 'example');
  };
  return <button onClick={storeData}>存储数据</button>;
}

// 页面B: 读取数据
function PageB() {
  const data = localStorage.getItem('sharedData');
  return <div>存储的数据: {data}</div>;
}

使用事件总线 自定义事件系统可以实现解耦的通信方式。

// eventBus.js
export const eventBus = {
  listeners: {},
  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => callback(data));
    }
  },
  on(event, callback) {
    if (!this.listeners[event]) this.listeners[event] = [];
    this.listeners[event].push(callback);
  }
};

// 页面A: 触发事件
import { eventBus } from './eventBus';
function PageA() {
  const sendEvent = () => {
    eventBus.emit('dataEvent', { message: 'Hello' });
  };
  return <button onClick={sendEvent}>发送事件</button>;
}

// 页面B: 监听事件
import { useEffect } from 'react';
import { eventBus } from './eventBus';
function PageB() {
  useEffect(() => {
    const handleEvent = data => {
      console.log('收到数据:', data);
    };
    eventBus.on('dataEvent', handleEvent);
    return () => eventBus.off('dataEvent', handleEvent);
  }, []);
  return <div>事件监听组件</div>;
}

使用window.postMessage 适用于跨窗口或iframe通信的场景。

// 父窗口发送消息
function ParentWindow() {
  const sendMessage = () => {
    window.frames[0].postMessage('Hello from parent', '*');
  };
  return <button onClick={sendMessage}>发送消息</button>;
}

// 子窗口接收消息
function ChildWindow() {
  useEffect(() => {
    const handleMessage = event => {
      console.log('收到消息:', event.data);
    };
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);
  return <div>消息接收方</div>;
}

方法选择建议

  • 简单数据传递:URL参数或浏览器存储
  • 复杂应用状态:Redux或Context API
  • 解耦通信:事件总线
  • 跨窗口通信:postMessage

每种方法都有适用场景,根据具体需求选择最合适的方案。URL参数适合简单临时数据,状态管理适合全局共享数据,浏览器存储适合持久化需求,事件系统适合组件解耦,postMessage适合跨域场景。

标签: 两个通讯
分享给朋友:

相关文章

vue实现消息通讯

vue实现消息通讯

vue实现消息通讯的方法 Vue中实现组件间消息通讯有多种方式,根据不同的场景和需求可以选择合适的方法。 使用Props和Events 父组件通过props向子组件传递数据,子组件通过$emit触发…

react如何动态绑定两个class

react如何动态绑定两个class

动态绑定两个 class 的方法 在 React 中,可以通过字符串拼接、模板字符串或第三方库(如 classnames)实现动态绑定多个 class。以下是具体实现方式: 字符串拼接或模板字符串…

java 如何比较两个字符串

java 如何比较两个字符串

比较字符串的内容是否相等 使用 equals() 方法比较两个字符串的内容是否相同。该方法区分大小写。 String str1 = "Hello"; String str2 = "hello"; b…

vue实现两个登录页面

vue实现两个登录页面

实现多个登录页面的方法 在Vue项目中实现两个不同的登录页面,可以通过路由配置和组件分离的方式完成。以下是具体实现步骤: 路由配置 在router/index.js文件中配置两个不同的路由路径指向不…

php实现服务通讯

php实现服务通讯

PHP 实现服务通讯的方法 使用 cURL 进行 HTTP 请求 cURL 是 PHP 中常用的 HTTP 客户端库,可用于与其他服务进行通讯。以下是一个简单的 GET 请求示例: $ch = cu…

vue实现父子通讯

vue实现父子通讯

Vue 父子组件通信方法 父组件向子组件传递数据(Props) 父组件通过 props 向子组件传递数据。子组件需要在 props 中声明接收的属性。 父组件模板: <template>…