【问题标题】:React Component fails to re-render after update from Redux Store从 Redux Store 更新后 React 组件无法重新渲染
【发布时间】:2018-06-15 00:55:48
【问题描述】:

谁能帮我弄清楚为什么我的组件在调度后没有更新?

function mapStateToProps(state) {
     const { isAuthenticated } = state
     return { isAuthenticated }
}

class LoginForm extends Component {

 handleSubmit(event) { 
        event.preventDefault();
        const { dispatch } = this.props
        const credentials = this.state
        dispatch(attemptLogIn(credentials)); 
}


//    Dispatch works properly when API validates Login:
//               Redux Log:  
//                nextState:{ authReducer: {isAuthenticated: true}}

render() {
    const { isAuthenticated } = this.props;
        return (
  <div>
    { isAuthenticated && <div> Authenticated: True </div> } 
                         // Does not render even after dispatch

      <form onSubmit={this.handleSubmit}>
     {... Form Stuff ...}
      </form>
    </div>
  )
}

export default withRouter(connect(mapStateToProps)(LoginForm))

只是来自 Redux 商店的简单条件渲染,我希望显示额外的 div 以通知用户他已通过身份验证,但它没有渲染。

Redux 异步教程中的 AsyncApp 示例中使用了这种类型的条件渲染示例,所以我不确定为什么它不起作用。我的动作被调度,reducers 成功更新状态,将其传递给连接的组件。这是我的减速器:

const initialState = { isAuthenticated: false}

const authReducer = (state = initialState, action) => {
    switch(action.type){
    case ('USER_AUTHENTICATED'): { 
        return Object.assign({}, state, {
            isAuthenticated: true,
            userPermissions: action.userInfo.userPermissions,
            instanceType: action.userInfo.instanceType
            }
        )
    }
    case ('INVALID_CREDENTIALS'): { 
        return Object.assign({}, state, {
            isAuthenticated:false
            }
        ) 
    }

    case ('LOG_OUT'): { 
        return initialState 
    }
    default:
            return state
    }
}

const rootReducer = combineReducers({
    authReducer,
    routerReducer
})

export default rootReducer

有谁知道为什么我的组件没有重新渲染?

【问题讨论】:

  • 在类 LoginForm 组件之外编写函数 mapStateToProps 表单。
  • @KuldeepSaxena 这是在这里发布代码的错误 - 我将重新编辑,我的 mapStateToProps 实际上在组件之外 - 我只是错误地将示例粘贴到这里:\
  • 请提琴
  • 正在处理它,加载所有依赖项需要一些时间
  • 你发布的reducer是你唯一的/root reducer吗?还是结合更多?

标签: javascript reactjs redux jsx conditional-rendering


【解决方案1】:

将您的 mapStateToProps 函数更改为此。

function mapStateToProps(state) {
 const { isAuthenticated } = state.authReducer;
 return { isAuthenticated };
}

【讨论】:

  • 所以,如果有多个 reducer,我必须始终指定从哪个 reducer 收集状态?
  • 是的,只定义那些你真正想要重新渲染你的组件的道具。为了获得更好的性能,请始终指定您的道具。例如。如果你有一个用户对象并且你只在你的渲染函数中使用它的一个特定属性,那么像这样定义它:username: state.user.name 而不是username: state.user
猜你喜欢
  • 2017-06-17
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多