【问题标题】:State doesn't have variable in react redux, variable not found on state状态在反应redux中没有变量,在状态上找不到变量
【发布时间】:2018-04-10 10:41:20
【问题描述】:

我正在使用 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);

我的 setCompleted 动作如下:

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

而我完成的Reducer如下:

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

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

谢谢

【问题讨论】:

  • ...state[completedChallenges] 在你的 reducer 中是一个变量。你的意思可能是state.completedChallengesstate['completedChallenges']
  • 您好 Andrew,感谢您的评论,我现在得到“Array.from 需要一个非空或未定义的类数组对象”。它似乎仍然没有设置任何东西?我不应该用空数组初始化它吗?
  • 抱歉,我想我现在在这里redux.js.org/docs/basics/Reducers.html 找到了答案,他们在那里设置了初始状态。抱歉,我是个菜鸟。

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


【解决方案1】:

也许你的意思是在你的减速器中:

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

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

另外,为什么你的组件中有一个状态?

【讨论】:

  • 嗨,Jalil,我要做的是添加已完成组件的列表,而不是覆盖它。例如:状态 1:已完成挑战 [A,B,C],然后我们完成挑战 D,状态 2:然后应该变为 [A,B,C,D] 而不仅仅是 D。
  • 那为什么不直接return [ ...state, action.completedChallenge] 将新挑战添加到列表中呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2019-03-19
  • 1970-01-01
  • 2021-05-21
  • 2023-03-14
  • 2020-02-22
  • 2016-11-06
相关资源
最近更新 更多