状态在反应还原中没有变量,在状态上找不到变量

时间:2017-10-29 09:10:29

标签: javascript react-native react-redux action store

我使用React redux在我的应用程序中存储状态。

我有以下组件:



import { connect } from 'react-redux';
import { setCompleted } from '../actions/completedActions';

class LoginScreen extends React.Component {

  static navigationOptions = {
    title: 'Login'
  };

  constructor(props) {
    super(props);
    this.state = {
      completedChallenges: []
    }
  }

  componentDidMount() {

  }


  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button onPress={this._handlePressAsync}>
            Hit me!
          <Button>
        </View>
      </View>
    );
  }

  _handlePressAsync = async () => {

    fetch(API + userInfo.id)
    .then((response) => response.json())
    .then((responseJSON) => {
      console.log(responseJSON);
      for (var i = 0; i < responseJSON.length; i++) {
        this.props.dispatch(setCompleted(responseJSON[i]));
      }
    })

  };

}

});

export default connect()(LoginScreen);
&#13;
&#13;
&#13;

我的setCompleted操作如下:

&#13;
&#13;
export const setCompleted = (completedChallenge) => {
  console.log("completed challenge in action");
  console.log(completedChallenge);
  return {
    type: 'SET_COMPLETED',
    completedChallenge
  }
}
&#13;
&#13;
&#13;

我的completedReducer如下:

&#13;
&#13;
const completedReducer = (state = [], action) => {
  console.log("completedReducer");
  console.log(state);
  switch(action.type) {
    case 'SET_COMPLETED':
      return [
        ...state,
          {
            completedChallenges: [
              ...state[completedChallenges],
              action.completedChallenge
            ]
          }
        ]
    default:
      return state
  }
}

export default completedReducer
&#13;
&#13;
&#13;

我已将reducer添加到combineReducers()函数中。当我运行代码并点击按钮时,执行会一直进入reducer,然后我收到错误"[Unhandled Promise rejection: ReferenceError: Can't find variable: completedChallenges]";这是有道理的,因为状态打印为[]。但是如何将完成的挑战添加到州?

由于

1 个答案:

答案 0 :(得分:0)

也许你的减速机意味着:

return [
  ...state, 
  { completedChallenges: [
    ...state[action.completedChallenge], 
    action.completedChallenge
   ] } 
]

即使我不确定你想要做什么...你期望什么减速器形状?

另外,为什么组件中有状态?