简体   繁体   中英

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. I did everything as in Redux docs about Store subscribing : https://redux.js.org/api/store#subscribe . Unfortunatelly, it's not working for me.

This is my 1st react project. (vue/x is better :] )

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. Reducer is working correctly, updates state after dispatching.

If you're using React, you should be using the React-Redux library to handle interacting with the 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.

Please create a script Store.js, and import for each component. When you use export, that will create a singleton from your export const:

Store.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); */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM