[英]Store subscribe not working in external component
So technically I have 2 components, I dispatch event from 1st, I want detect this change in 2nd.所以从技术上讲,我有 2 个组件,我从第 1 个分派事件,我想在第 2 个中检测到这种变化。 I did everything as in Redux docs about Store subscribing : https://redux.js.org/api/store#subscribe .
我做了所有关于商店订阅的 Redux 文档: https : //redux.js.org/api/store#subscribe 。 Unfortunatelly, it's not working for me.
不幸的是,它对我不起作用。
This is my 1st react project.这是我的第一个反应项目。 (vue/x is better :] )
(vue/x 更好:])
import React, {Component} from 'react';
import reducers from '../../reducers'
import { Dropdown } from 'semantic-ui-react'
import {translate} from "../../actions";
import createStore from "../../createStore";
const store = createStore(reducers)
class Component1 extends Component {
componentDidMount() {
store.subscribe(() => console.log(1));
}
updateTexts(lang) {
store.dispatch(translate(lang));
}
render() {
this.dropdown = <Dropdown
onChange={this.updateTexts}
/>
return (
<div className={"lang-switcher"}>
<div className={"select-lang"}>
{this.dropdown}
</div>
</div>
);
}
}
export default Component1
import React, {Component} from 'react';
import axios from 'axios';
import {Animate} from 'react-animate-mount';
import createStore from "../../createStore";
import reducers from "../../reducers";
const store = createStore(reducers);
export default class Component2 extends Component {
componentDidMount() {
store.subscribe(console.log(2));
}
render() {
return (
<div className="box">
{Something}
</div>
);
}
}
I want that Component2 will detect state change done by Component1.我希望 Component2 将检测到 Component1 完成的状态更改。 Reducer is working correctly, updates state after dispatching.
Reducer 工作正常,调度后更新状态。
If you're using React, you should be using the React-Redux library to handle interacting with the store .如果你使用 React,你应该使用 React-Redux 库来处理与 store 的交互。
That said, it also looks like you're creating two different store instances, one in each component file.也就是说,看起来您正在创建两个不同的商店实例,一个在每个组件文件中。 So, Component 2 doesn't know about the store instance in Component 1's file.
因此,组件 2 不知道组件 1 文件中的商店实例。
Please create a script Store.js, and import for each component.请创建一个脚本 Store.js,并为每个组件导入。 When you use export, that will create a singleton from your export const:
当您使用导出时,这将从您的导出常量创建一个单例:
Store.js商店.js
import reducers from '../../reducers'
import createStore from "../../createStore"
export default createStore(reducers)
and use as:并用作:
import store from "./Store";
/* REMOVE const store = createStore(reducers); */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.