React Redux - 如何从静态函数访问结构化选择器?

问题描述 投票:2回答:1

我想从一个班级访问州。让我试着用代码告诉我。

import React from 'react';
import { makeSelectTranslations } from 'containers/App/selectors.js';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';

class Translation extends React.Component {

    static translate(value) {
        return this.props.translations[value];
    }
}


Translation.propTypes = {
    dispatch: PropTypes.func.isRequired,
  };

  const mapStateToProps = createStructuredSelector({
    translations:makeSelectTranslations(),
  });

  function mapDispatchToProps(dispatch) {
    return {
      dispatch,
    };
  }

  export default connect(mapStateToProps, mapDispatchToProps)(Translation);

我想像这样使用这个翻译库:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Translation from 'libraries/Translation';

export class MainPage extends React.Component {
  render() {
    return (
        <div>{Translation.translate('hello_world')}</div>
    );
  }
}

MainPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  MainPage: makeSelectMainPage(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(MainPage);

这是我的选择器

const selectGlobal = () => (state) => state.get('global');

const makeSelectTranslations = () => createSelector(
  selectGlobal(),
  (globalState) => globalState.get('translations')
);

以下是我的翻译地址:

所以,我的目标是在我项目的每个地方使用Translation.translate('hello_world')。这可能吗?

谢谢

reactjs redux react-redux
1个回答
3
投票

React组件旨在解决用户界面实现问题,但您尝试做的事情更像是依赖于应用程序状态的服务

请记住,redux它是一个与React分离的状态容器,而react-redux有助于它们协同工作。

建议


The same way you initialize you app with react-redux:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import App from './components/App';
import store from './store';

ReactDOM.render((
    <Provider store={store}>
      <App />
    </Provider>
  ), document.getElementById('root'));

您可以通过以下方式初始化翻译服务:

import store from './store';

export default function translate(key) {
  const state = store.getState();
  const translations = state.get('global').get('translations').toJS();

  return translations[key] || `*${key}*` ;
}

然后以这种方式在组件中的任何地方使用它:

import React from 'react';
import translate from 'service/translate'; // wherever you put the service

class MainPage extends React.Component {
  render() {
    return (
        <div>{translate('hello_world')}</div>
    );
  }
}

export default MainPage;

查看Store API以获取更多信息https://redux.js.org/docs/api/Store.html

© www.soinside.com 2019 - 2024. All rights reserved.