G
G
glebvvs2018-09-14 23:20:38
React
glebvvs, 2018-09-14 23:20:38

Why is React component not rerendering after dispatch in Redux?

The problem is that after the dispatch, changes occur in the connect() decorator in redux and these changes can be caught, for example, if you directly subscribe to redux and get the state of the store, but the properties of the component itself that called the dispatch does not change and the component is not re-rendered. ..
What could be the problem?
Here is my main component...

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Login from './auth/Login'
import Registration from './auth/Registration'
import { Provider } from 'react-redux';
import { createStore } from 'redux';

let myStore = function(state = ['test'], action) {
  if ( action.type === 'ADD_TEXT' ) {
    state.push(action.payload);
    return state;
  }
  return state;
};

const store = createStore(myStore);

store.subscribe(() => {
  console.log(store.getState());//после dispatch внутри компонента Login состояни ехранилища меняется
});

export default class Main extends Component {

  constructor(props) {
    super(props);
  }

  renderForGuest() {
    return (
      <Provider store={store}>
        <div className="auth">
          <Login />
          <Registration />
        </div>
      </Provider>
    );
  }

  render() {
    return this.renderForGuest();
  }
}

//here is the component where the dispatch to the redux is called
import React, { Component } from 'react';
import { connect } from 'react-redux';

class Login extends Component {

  constructor(props) {
    super(props);

    this.state = {
      errorMessagesForForm: null
    };
  }

  submitForm(event) {
    event.preventDefault();
    this.props.onSubmitForm();


  }

  render() {
    return (
      <div className="login">

        <ul>
          {
            this.props.testStore.map((text, index) => (
              <li key={index}>{text}</li>
            ))//а этот список не перерендеривается после dispatch
          }
        </ul>

        <form>
          <div><input className="form-field" type="text" placeholder="username" /></div>
          <div><input className="form-field" type="password" placeholder="password" /></div>
          <button onClick={this.submitForm.bind(this)}>Login</button>
        </form>
      </div>
    );
  }

}

export default connect(
  state => ({
    testStore: state
  }),
  dispatch => ({
    onSubmitForm: () => {
      dispatch({type: 'ADD_TEXT', payload: 'wtf'});
    }
  })
)(Login);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
webe, 2018-09-15
@glebvvs

glebvvs ,

state.push(action.payload);
    return state;

replace with:
return [...state, action.payload];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question