我正在使用一个组件来翻译屏幕上的文本。
这是我的T课
//Redux store located in app.js
import { store } from "app.js";
export default class T {
/**
* finds the variable in store and returns the translation if exists.
* @param {String} key
*/
static _(key) {
const state = store.getState();
const translations = state.get("global").get("translations");
if (translations[key]) {
return translations[key];
}
return `*${key}*`;
}
}
我正在这样使用这个类
import T from 'libraries/T';
import React from 'react';
export default MyClass extends React.Component {
render(){
return (<div>Here we write translation of name : {T._('name')}</div>)
}
}
我的问题从这里开始,用户可以使用标题中的下拉菜单更改语言。当用户更改下拉列表时,我会更新商店中的语言日期。 但页面不会呈现新值。当我转到其他页面时,可以看到新的语言值。
但我想在 saga 或 reducer 中重新渲染页面。这可能吗?
最佳答案
据我所知,您直接从组件内部访问存储,并且它无法检测到任何状态更改,因为它尚未订阅 Redux 存储,我建议您使用 react Redux。 ( github ,带有存储库和文档)
使用 React Redux
,您可以使用 connect
API 来包装您的组件,为其订阅 Redux 存储的任何更改,然后从存储中提取所需的状态并触发组件的渲染,将该状态作为 props 传递。使用 mapStateToProps
函数 ( documentation ) 提取所需的状态。
我建议阅读、理解和使用 React Redux
,因为它有一个相对简单的 API,但非常强大和有用。
此外,在您的代码中,您可以在 MyClass
组件中使用 connect
,通过传递给 mapStateToProps
来提取所需的状态code>connect 并将该状态作为 props 传递。这样您可能不需要 T
类,您可以使用 mapStateToProps
函数实现相同的任务(该函数将具有与 _ (键)
方法)。
关于javascript - 如何在 React 上使用 Redux 重新渲染所有页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48816253/