反应本机redux能够读取值但无法在同一页面中更新值

时间:2019-05-27 08:27:23

标签: react-native redux expo

当动作似乎分派给reducer函数时,我能够读取redux store(Props)的值,​​但无法更新redux状态值(Props2)。

enter image description here

页面:

componentDidMount(){
    console.log("Props:"+this.props.user)
}

dummyFunction() {
    //Redux
    this.props.toggleTheme('red');

    //which prints the object above in the screenshot
    console.log(this.props.toggleTheme('red'));    

    console.log("Props2:"+this.props.user);
}

const mapStateToProps = state => ({
  user: state.user.userData,
});

const mapDispatchToProps = dispatch => ({
  toggleTheme: (user) => dispatch(toggleTheme(user)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Tab1Screen);

减速器:

const initialState = {
    userData: "Apple",
  };

  const user = (state = initialState, action) => {
    switch (action.type) {
      case 'TOGGLE_THEME':
        switch(action.payload) {
          case 'red':
            console.log("Payload1:"+ action.payload);
            return { userData: "Orange" };
          case 'blue':
          console.log("Payload2:"+ action.payload);
            return { userData: "Pear" };
        }
      default:
      console.log("Payload:3"+ action.payload);
        return state;
    }
  };

  export default user;

动作:

import { TOGGLE_THEME } from './actionTypes';
//which TOGGLE_THEME = 'TOGGLE_THEME'

export const toggleTheme = user => ({
  type: TOGGLE_THEME,
  payload: user,
});

Package.json

 "dependencies": {
    "@expo/samples": "2.1.1",
    "expo": "^32.0.0",
    "react": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-navigation": "^3.0.9",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
  }

更新:当我导航到另一页并且其工作正常时,尝试检索状态,并检索橙色值。我如何能够在同一页面(在dummyFunction中)获得正确的值?

1 个答案:

答案 0 :(得分:1)

我不确定您是否可以在设置更改后的redux状态(立即分发操作)后立即获得它。

您可以做的是: