【问题标题】:React native redux able to read value but unable to update value in the same pageReact native redux 能够读取值但无法在同一页面中更新值
【发布时间】:2019-05-27 08:27:22
【问题描述】:

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

页面:

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,
});

包.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 中)?

【问题讨论】:

  • 我想说不是在你的 reducer 中返回一个新的 state obj,你可以像 return {...state, userData: "Orange"} 那样修改它,为了调试目的,尝试简化你的 switch 语句,看看出了什么问题
  • 嗨@AmrAly,我试过......状态无济于事。奇怪的是,一旦您导航到另一个页面,就会检索更新的值,这意味着 switch 语句工作正常。
  • this 的回答中,这个家伙说你不能只用控制台登录相同的功能,而是可以在componentWillReceiveProps 中进行操作
  • 即使我第二次调用该函数,它仍然显示“红色”。我猜它更倾向于“mapStateToProps”而不是刷新。
  • 你可以像这样控制台日志:const mapStateToProps = state => ( console.log('state:',state); return { user: state.user.userData, });

标签: react-native redux expo


【解决方案1】:

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

你可以做的是:

【讨论】:

  • 我认为他试图在同一函数dummyFunction 中捕获更改但应该根据您的回答在生命周期方法中检测到的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2021-09-01
相关资源
最近更新 更多