1

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

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

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

4

1 回答 1

1

将您的 mapStateToProps 函数更改为此。

function mapStateToProps(state) {
 const { isAuthenticated } = state.authReducer;
 return { isAuthenticated };
}
于 2018-01-05T08:45:32.540 回答