javascript - 在 reducer 中设置值时,Prop 未按预期更新

标签 javascript react-native redux

我在测试我新创建的 action 和 reducer 时遇到了这个问题。即使我在我的 reducer 中将其设置为固定值,prop 也不会更新。

组件:

class <ComponentName> extends Component {

    componentDidMount() {
        login()
    }
    
    render() {
        if(this.props.isLogged) 
            return (
                <App/>    
            );
        else 
            return (
                <ErrorScreen/>
            );
    }    
}



function mapStateToProps(state) {
    return {
      isLogged:state.auth.isLogged
    }
}


const mapDispatchToProps = (dispatch) => {
    return {
        login: () => dispatch(login())
    };
};

  
export default connect(mapStateToProps,mapDispatchToProps)(<ComponentName>)

行动:

export function login() {
    return {
        type:"TEST"
    }
}

reducer :

const initState = {
    isLogged: false,
    
}

export default (state=initState, action) => {
    switch(action.type) {
        case "TEST":
            return {
                ...state,
                isLogged: true
            }
            break;
    default:
        return state     
    }
} 

联合 reducer :

import {combineReducers} from 'redux'
import AuthenticationReducer from './authenticationReducer'

export default combineReducers({
    auth: AuthenticationReducer
})

提供者:

import React, {Component} from "react";
import <ComponentName> from './app/screens/<ComponentName>'
import store from './app/store'
import {Provider} from 'react-redux'

export default () =>
<Provider store={store}>
  <<ComponentName>/>
</Provider>;

一段时间以来一直在尝试调试它。我仍然不知道为什么会这样。也许我错误地实现了它?如果有一些我忘记包含的文件,请通知我。谢谢,祝你有美好的一天!

最佳答案

您的代码未按预期工作的原因是因为您正在调用 login() Action 创造者,而不是 login()mapDispatchToProps() 返回的方法(并注入(inject)到 props<ComponentName/> 中)。

尝试通过添加 this.props 来修改您的代码在您调用 login() 之前像这样:

class <ComponentName> extends Component {

    componentDidMount() {

        // Update this line here so that the login() method 
        // injected by connect() is called (ie via this.props)
        this.props.login()
    }

    render() {
        if(this.props.isLogged) 
            return <App/>
        else 
            return <ErrorScreen/>
    }    
}

关于javascript - 在 reducer 中设置值时,Prop 未按预期更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292632/

相关文章:

javascript - 在页面渲染react-native hooks之前从api获取数据

javascript - 使用 TypeScript 在 React 组件之外调度 Redux Thunk 操作

javascript - 函数闭包中的另一个 jQuery 版本

javascript - 使用 javascript 和 getElementsByClassName 检索显示属性

javascript - 如何在这种情况下进行多次工作

javascript - 在复选框选择列表中使用链接列表 react native

javascript - 从其他类访问静态方法是标准的吗?

react-native - 尝试在 React-Native Firebase 中使用电话身份验证时,iOS 模拟器中的应用程序崩溃

javascript - 如何从子组件调用父组件中的方法?

javascript - 使用 reducer 更新状态内的特定值