我想从一个类访问状态。让我试着用代码告诉你。
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')。这可能吗?
由于
答案 0 :(得分:3)
React组件旨在解决用户界面实现问题,但您尝试做的事情更像是依赖于应用程序状态的服务
请记住,redux是一个与React
分离的状态容器,而react-redux
有助于它们协同工作。
<小时/> 与使用
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;
检查商店API以获取更多信息https://redux.js.org/docs/api/Store.html