React-redux component does not rerender on store state change

后端 未结 2 1168
轻奢々
轻奢々 2020-12-09 09:31

I\'m stating to learn react and redux today, yet I cannot figure out how to force component to rerender after state change.

Here is my code:

const s         


        
相关标签:
2条回答
  • 2020-12-09 09:39

    Your component is only going to re-render if its state or props are changed. You are not relying on this.state or this.props, but rather fetching the state of the store directly within your render function.

    Instead, you should use connect to map the application state to component props. Component example:

    import React, { PropTypes } from 'react';
    import { connect } from 'react-redux';
    
    export class App extends React.Component {
        constructor(props, context) {
            super(props, context);
        }
    
        render() {
            return (
                <div>
                {this.props.isLoggedIn ? 'Logged In' : 'Not Logged In'}
                </div>
            );
        }
    }
    
    App.propTypes = {
        isLoggedIn: PropTypes.bool.isRequired
    };
    
    function mapStateToProps(state, ownProps) {
        return {
            isLoggedIn: state.isLoggedIn
        };
    }
    
    export default connect(mapStateToProps)(App);
    

    In this very simplified example, if the store's isLoggedIn value changes, it will automatically update the corresponding prop on your component, which will cause it to render.

    I suggest reading the react-redux docs to help you get started: https://redux.js.org/basics/usage-with-react

    0 讨论(0)
  • 2020-12-09 09:44

    I ended up here because I had written a bad reducer. I had:

    const reducer = (state=initialState, action) => {
      switch (action.type) {
        case 'SET_Q':
          return Object.assign(state, {                     // <- NB no {}!
            q: action.data,
          })
    
        default:
          return state;
      }
    }
    

    I needed:

    const reducer = (state=initialState, action) => {
      switch (action.type) {
        case 'SET_Q':
          return Object.assign({}, state, {                 // <- NB the {}!
            q: action.data,
          })
    
        default:
          return state;
      }
    }
    
    0 讨论(0)
提交回复
热议问题