【问题标题】:functional component is not re-rendering when redux state changes当 redux 状态发生变化时,功能组件不会重新渲染
【发布时间】:2021-06-12 12:25:25
【问题描述】:

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

当复选框被选中时,redux 状态会正确更改,但组件不会重新渲染并且 props 不会更新

我知道我应该使用钩子,但现在,我想了解为什么不重新渲染这个组件?因为我还有其他一些类似的组件,它们可以正确处理 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

【问题讨论】:

    标签: javascript reactjs redux react-functional-component


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多