Redux动作会更新状态,但随后会立即将其自身反转为null?

时间:2018-10-03 20:23:59

标签: react-native redux react-redux

我正在尝试从集合中选择一个随机对象,并使用其值更新状态;这一切都在redux中完成。我遇到的问题是我得到了我的随机对象,但是一旦操作完成,状态就会回到null。这是我在做什么:

1)我用一个功能创建了一个动作文件。单击应用程序的按钮后,便会触发此操作。

import { mapData } from '../../mapData';

export const getRandomMap = (mapPlayerCount) => dispatch => {
  // get a collection of 1v1, 2v2, 3v3, or 4v4 maps based on the map player count
  const maps = Object.values(mapData).filter(map =>
    map.players === mapPlayerCount
  );

  const min = 0;
  const max = maps.length;
  const randomIndex = Math.floor(Math.random() * (max - min + 1)) + min;
  dispatch({ type: 'GET_RANDOM_MAP', randomMap: maps[randomIndex] });
}

2)派遣带我到用于更新状态的reducer文件。

const INITIAL_STATE = {
  randomMap: null
};

const mapReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case 'GET_RANDOM_MAP': {
      return {
        ...state,
        randomMap: action.randomMap
      };
    };

    default: {
      return state;
    };
  };
};

export default mapReducer;

3)这是带有按钮的实际屏幕,该屏幕触发操作(被截断的无关代码)

import { getRandomMap } from '../redux/actions/map_actions';
import { connect } from 'react-redux';

class RandomMapPickerScreen extends Component {
  state = {
    ...
  }

  handleSelection = (selectedIndex) => {
    ...
  }

  handleRandomMapRequest = () => {
    switch (this.state.selectedIndex) {
      case 0: {
        // 2 player maps / 1v1
        this.props.getRandomMap(2);
        break;
      }
      case ...
    }
    console.log(this.props.randomMap)

    //this.setState({ showPropThumbnail: false })
  }

  render() {
    ...
  }
}

const mapStateToProps = state => ({
  randomMap: state.map.randomMap
});

export default connect(mapStateToProps, {
  getRandomMap
})(RandomMapPickerScreen);

const styles = StyleSheet.create({...});

让我向您介绍调试器中的内容: 1)我单击按钮,然后转到操作 enter image description here enter image description here

2)该应用程序遍历了所有reducer,并使用新的randomMap值正确更新了状态 enter image description here

3)然后将我带回到屏幕文件,我可以清楚地看到具有正确值的randomMap enter image description here

4)分派在我的动作文件中完成 enter image description here

5)代码将我带回到主屏幕文件,但是这一次,randomMap是默认的NULL值...为什么会发生这种情况?我的randomMap不应该保留该值吗? enter image description here

1 个答案:

答案 0 :(得分:2)

您是否正在尝试在分发动作后立即查看道具的内容?如果是这样,React还没有机会重新渲染组件,因此该道具将仍然具有旧值。

从概念上讲,这与尝试立即查看状态更改的内容非常相似,例如:

// assume it's previously {a : 1}
this.setState({a : 42});
console.log(this.state.a) // 1, not 42

因为setState()通常是异步的。