当 redux 状态改变时,功能组件不会重新渲染

时间:2021-03-15 08:26:06

标签: javascript reactjs redux react-functional-component

当 redux 状态改变时,我的一个功能组件不会重新渲染:

选中复选框后,redux 状态会正确更改,但组件不会重新渲染且道具不会更新

我知道我应该使用钩子,但现在,我想了解为什么不重新渲染此组件?因为我还有其他一些像这样的组件,它们可以正确处理 redux 状态

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

1 个答案:

答案 0 :(得分:1)

尝试返回一个新状态而不是改变当前状态

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

当您返回时只是状态。 Redux 将忽略任何突变,因为它使用浅比较。

在此处阅读更多信息: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