Redux mapStateToProps只调用一次

问题描述 投票:2回答:2

在我的反应原生应用程序中实施redux的问题已经过去了2天。我检查了很多主题,但我无法解决我的问题。

问题是mapStateToProps只被调用一次,但在执行动作后不再调用它。我的减速器被调用,但状态没有更新。

我用android studio和emulator测试我在android上的工作。

这是我的代码:

App.js:

  <Provider store={createStore(reducers)}>
    <View>
         <MainScreen />
    </View>
  </Provider>

HeaderReducer:

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case SET_HEADER:
      return action.payload;
    default:
      return state;
 }

};

减速器/ index.js

import { combineReducers } from 'redux';
import HeaderReducer from './HeaderReducer';

export default combineReducers({
  headerText: HeaderReducer,
});

动作/ index.js

export const SET_HEADER = 'set_header';

export const setHeaderText = (title) => {
  return {
    type: SET_HEADER,
    payload: title,
  };
};

MainScreen.js

import * as actions from '../actions';

... 
<Text> {this.props.headerText} </Text>
<Button
          onPress={() => {
            this.props.setHeaderText(`screen: ${SELECTED_PAGE.profile}`);
            this.forceUpdate();
          }}
        >

 ...

const mapStateToProps = (state) => {
  const { headerText } = state;
  return { headerText };
};

export default connect(mapStateToProps, actions)(MainScreen);

我知道我不需要在onPress回调中强制更新,但只是在调用函数后检查状态。

因此,当应用程序启动时,调用reducers并且我的mapStateToProps正在运行。但是当我点击我的按钮时,我的减速器被调用,好的动作在开关中执行但我的mapStateToProps不再被调用。当我第二次点击如果我在控制器中记录我的reducer中的状态时,我可以看到状态没有更新,但保持与INITIAL_STATE相同。

我没有在我的Reducer中改变状态,我在MainScreen.js中连接了所有内容,然后我将应用程序包装在Provider with store中。

我按照Udemy的教程在我的应用程序中实现redux,甚至我在github上检查tuto的代码,我找不到问题的来源(qazxsw poi)

我想我错过了一些非常明显的东西,但我从2天后就找不到出错的地方:/

如果有人可以提供帮助,我会很感激:)

谢谢。

编辑:

我没有弄清楚问题,所以我只是从头开始重新开始,我做了完全相同的(THE SAAME !!)并且它现在正在工作...感谢您的帮助:)

react-native redux
2个回答
1
投票

问题出在你的https://github.com/StephenGrider/ReactNativeReduxCasts/tree/master/tech_stack中,reducer期望返回一个状态对象,但你要返回一个字符串。

HeaderReducer

export default (state = INITIAL_STATE, action) => { switch (action.type) { case SET_HEADER: return action.payload; default: return state; } 的情况下,你真正想要的是覆盖一个字段而不是覆盖整个状态对象,所以改为下面而不是

SET_HEADER

然后在你的const INITIAL_STATE = { customizeText: '' }; export default (state = INITIAL_STATE, action) => { switch (action.type) { case SET_HEADER: return { ...state, customizeText: action.payload }; // <<=== HERE default: return state; } } ,你必须更新你的MainScreen.js功能

mapStateToProps

我已经更新了字段名称以避免混淆


0
投票

首先将实际操作作为<Text> {this.props.someText} </Text> ... const mapStateToProps = ({ headerText }) => { return { someText: headerText.customizeText }; }; ... 并传递标题,如果您愿意并确保您的INITIAL_STATE是对象或[]。

this.props.setHeaderText()
© www.soinside.com 2019 - 2024. All rights reserved.