简体   繁体   中英

functional component is not re-rendering when redux state changes

one of my functional components is not re-rendering when the redux state changes:

when the checkbox is checked the redux state changes properly but the component does not re-render and props do not update

I know I should use hooks but for now, I want to understand why this component is not re-rendered? cause I have some other components like this one and they work with redux states properly

Panel9.js:

import { connect } from 'react-redux'
import { registeredUserInput } from '../../actions'

function Panel9(props) {
 return (
  <div>
    <input type="checkbox" onClick={(e) => props.registeredUserInput(e.target.checked)}/>
    <span>search key</span>
    <label for="sNum">from</label>
    <input type="number" id="sNum" name="eNum" placeholder="1"/>
    <label for="eNum">to</label>
    <input type="number" id="eNum" name="eNum" placeholder="10000" />
  </div>
 )
}
const mapStateToProps = state => {
 return {
    tableBooleans: state.tableReducer
 }
}

const mapDispatchToProps = dispatch => {
 return {
    registeredUserInput: bool => dispatch(registeredUserInput(bool))
  }
 }

 export default connect(mapStateToProps, mapDispatchToProps)(Panel9)

tableReducer.js:

 const initialState = {
 registeredInput: false,
 phoneUserInput: false
}

const tableReducer = (state = initialState, action) => {
  //console.log(state, action)
  switch (action.type) {
     case 'REGISTERED_USER_INPUT':
         state.registeredInput = action.bool
         return state
     case 'PHONE_USER':
         return state
     default:
         return state
  }
}

export default tableReducer

Try return a new state instead of mutating current state

case 'REGISTERED_USER_INPUT':  
    return {
        ...state,
        registeredInput: action.bool
    }

When you return just state . Redux will ignore any mutation because it use shallow compare.

Read more here: https://redux.js.org/faq/immutable-data#:~:text=React%2DRedux%20performs%20a%20shallow,on%20the%20props%20object%20itself.&text=As%20such%2C%20a%20shallow%20equality,would%20be%20returned%20each%20time .

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