当前位置:首页 > 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 向子组件传递…

vue实现串口通讯

vue实现串口通讯

Vue 实现串口通信的方法 Vue 本身不直接支持串口通信,但可以通过 Web Serial API 或第三方库实现。以下是几种常见方法: 使用 Web Serial API(浏览器环境)…

react如何实现两个FORM

react如何实现两个FORM

实现两个表单的基本结构 在React中创建两个表单可以通过分别定义两个独立的表单组件实现。每个表单应包含自己的状态管理和提交逻辑。 function Form1() { const [formD…

react如何合并两个数组

react如何合并两个数组

合并两个数组的方法 在React中合并两个数组可以使用多种方法,以下是一些常见的方式: 使用扩展运算符(Spread Operator) const array1 = [1, 2, 3]; c…

react两个组件如何传值

react两个组件如何传值

父组件向子组件传值 通过 props 传递数据。父组件在调用子组件时通过属性传递值,子组件通过 props 接收。 父组件示例: import ChildComponent from…