【问题标题】:State and routing for imported React components导入的 React 组件的状态和路由
【发布时间】:2017-08-28 20:12:10
【问题描述】:

我必须编写一个具有两个版本的集成聊天模块 - 一个小的站点内窗口(如 facebook messenger)和在新选项卡中打开的完整版本(新的 react-router 路由)。因此,该模块导出两个组件:<ChatWindow /><ChatFullView /> 分别用于这些视图。

// core application
import {ChatWindow, ChatFullView} from 'chat-module';


// <PageContentWithChat /> contains imported <ChatWindow />
<Switch>
    <Route path='/' component={PageContentWithChat} />
    <Route path='/fullview' component={ChatFullView} />
</Switch>

所以,问题是:
我应该在哪里声明 redux 存储并为它们管理它? (他们必须有一个统一的商店,因为来自窗口版本的消息应该以全视图呈现,反之亦然)

编辑: 我想从内部控制模块:

// in module
const store = createStore(reducer);

....
<Provider store={store}>
    <ChatWindow />
    <ChatFullView />
</Provider>

但恐怕我无法单独导出这些组件,因为它们是用&lt;Provider /&gt; 包裹的。怎么可能解决这个问题?

【问题讨论】:

  • 如果chat-module 已经这样做了,为什么还需要单独导出?

标签: javascript reactjs redux react-router


【解决方案1】:

react-redux 通过 Provider 组件通过上下文使 store 可用。

假设&lt;ChatWindow /&gt;&lt;ChatFullView /&gt; 是连接的组件,您可以将所有内容包装在&lt;Provider /&gt; 中,作为道具传入您的商店。

当然,您可以将所有这些组织到不同的文件中,但这是一般的想法。

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Switch, Route } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { createStore } from 'redux';
import PageContentWithChat from 'path-to-page-content-with-chat';
import { ChatWindow, ChatFullView } from 'chat-module';

const store = createStore(/* reducers + initial message state passed in here... */);
const container = document.getElementById(/* id of your app container */);
const component = (
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path='/' component={PageContentWithChat} />
        <Route path='/fullview' component={ChatFullView} />
      </Switch>
    </BrowserRouter>
  </Provider>
);

render(component, container);

【讨论】:

  • 是否可以从同一个模块中导入reducer并封装所有属于聊天应用程序的动作和常量?
  • @MichaelReyfman 如果您正在谈论从chat-module 导出reducer 的方式与导出ChatWindowChatFullView 的方式相同,那么可以。您可以从模块中导出任意数量的内容。
猜你喜欢
  • 2018-11-26
  • 1970-01-01
  • 2022-01-21
  • 2017-04-25
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
相关资源
最近更新 更多