2017-04-03 90 views
0

这就是所讨论的组件。在组件挂载之前,它会成功分派一个操作{this.props.populateGrid()}。一切都很好,我可以在记录器中看到状态(基本上它是随机数的嵌套数组)。当我按下按钮时,它应该用新的随机数重新水化状态。但是,我收到以下错误:无法读取未定义的属性'populateGrid'。react-native redux重新填充状态

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

回答

1

我认为你需要绑定thisrefresh方法在你onClick处理程序,使this设置正确refresh执行时:

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

希望帮助!

+0

当然是这样的。谢谢 – Wasteland