简体   繁体   中英

React app not rerender after store state changed

My component is not rerendering after the store is changing. I make sure that the store is actually changing by dropping him to the console with store.subscribe() and console.log(store.getState()) but still the component is not rerendering again. I will appreciate your help.

configureStore.js

import { createStore, combineReducers } from 'redux';
import home from '../reducers/home';
import favorites from '../reducers/favorites';

export default () => {
    const store = createStore(combineReducers({
        home,
        favorites
    }))

    return store;
}

App.js

import React from 'react';
import ReactDOM from 'react-dom';

import { Provider } from 'react-redux';
import configureStore from './redux/store/configureStore';
import AppRouter from './router/AppRouter';

const store = configureStore();

const jsx = (
    <Provider store={store}>
        <AppRouter />
    </Provider>
);

ReactDOM.render(jsx, document.querySelector('#root'));

home.js (reducer)

const homeDefaultState = {
    name: 'someName'
}

export default (state = homeDefaultState, action) => {
    switch (action.type) {
        case 'CHANGE_NAME':
            return {
                ...state,
                name: 'otherName'
            }
        default:
            return state;
    }
}

home.js (action)

export const changeName = () => ({
    type: 'CHANGE_NAME'
})

Home.js (component)

import React from 'react';

import configureStore from '../../redux/store/configureStore';
import { changeName } from '../../redux/actions/home';
import { connect } from 'react-redux';

const store = configureStore();

const handleName = () => {
    store.dispatch(changeName())
}

const Home = (props) => (
    <div className="home">
        <button onClick={handleName}>
            change name
        </button>

        {props.home.name}
    </div>
);

const mapStateToProps = (state) => ({
    home: state.home
});

export default connect(mapStateToProps)(Home);

In your Home component you initialize store for second time. And bound action to this second store

const store = configureStore();

const handleName = () => {
    store.dispatch(changeName())
}

At the same time with connect() you access store declared in App.jsx

Read from first but update second. Just remove second store and use mapDispatchToProps ( second parameter passed to connect() ) instead:

const mapStateToProps = (state) => ({
    home: state.home
});

export default connect(mapStateToProps, { handleName: changeName })(Home);

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