react-native redux 重新填充状态

react-native redux repopulate the state

这就是有问题的组件。在挂载组件之前,它成功地调度了一个动作 {this.props.populateGrid()}。一切都很好,我可以在记录器中看到状态(基本上它是一个嵌套的随机数数组)。当我按下按钮时,它应该用新的随机数重新调整状态。然而,我收到以下错误:无法读取 属性 'populateGrid' of undefined.

import React, { Component, PropTypes } from 'react';
import { View, StyleSheet, Button } from 'react-native';
import Grid from './Grid';
import * as globalStyles from '../styles/global';


export default class Body extends Component {

  componentWillMount() {
    this.refresh();
  }

  refresh() {
    this.props.populateGrid();
  }
  render() {
    return (
      <View style={styles.body}>
        <Grid inGrid={this.props.grid} />
        <Button
          onPress={this.refresh}
          title={'Regenerate the Grid'}
        />
      </View>
    );
  }

}

容器:

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import { listNumbers, pickNumber } from '../actions/numberActions';
import { populateRow, populateGrid } from '../actions/gridActions';
import Body from '../components/Body';

const mapStateToProps = state => ({
  numbers: state.numbers,
  grid: state.grid
});

const mapDispatchToProps = dispatch => (
  bindActionCreators({
    listNumbers,
    pickNumber,
    populateRow,
    populateGrid
  }, dispatch)
);

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

操作:

import { POPULATE_ROW, POPULATE_GRID } from './actionTypes';
import { randNumbers, randGrid } from '../utils/generators';

export const populateRow = (n) => {
  return {
    type: POPULATE_ROW,
    payload: randNumbers(n)
  };
};

export const populateGrid = () => {
  return {
    type: POPULATE_GRID,
    payload: randGrid()
  };
};

减速器:

import { POPULATE_ROW, POPULATE_GRID } from '../actions/actionTypes';

export default (state = [], action = {}) => {
  switch (action.type) {
    case POPULATE_ROW:
      return action.payload || [];
    case POPULATE_GRID:
      return action.payload || [];
    default:
      return state;
  }
};

数字生成器(在本例中是第二个函数)

export const randNumbers = (n) => {
  let numbers = new Array(n);
  const shuffled = [];

  // fill one array with the numbers 1-10
  numbers = numbers.fill(1).map((_, i) => i + 1);

  // shuffle by taking a random element from one array
  // and pushing it to the other array
  while (numbers.length) {
    const idx = numbers.length * Math.random() | 0; // floor trick
    shuffled.push(numbers[idx]);
    numbers.splice(idx, 1);
  }
  return shuffled;
};

export const randGrid = () => {
  const shuffled = randNumbers(6);
  const array = shuffled.map(a => {
        let r = new Array(6);
        r = [a, ...randNumbers(5)];
        return r;
    });
  return array;
};

我认为您需要将 this 绑定到 onClick 处理程序中的 refresh 方法,以便在 refresh 执行时正确设置 this :

<Button
  onPress={this.refresh.bind(this)}
  title={'Regenerate the Grid'}
/>

希望对您有所帮助!