TypeError:.push未定义

时间:2019-04-21 01:34:09

标签: javascript reactjs react-native redux react-redux

我创建了一个redux数据存储区,我希望基本上存储用户喜欢或不喜欢的宠物的索引。我遇到一个错误,即TypeError:.push未定义时出现错误。我正在遵循此处提到的基本Redux教程https://www.youtube.com/watch?v=KcC8KZ_Ga2M 我对数组先定义然后在将整数推入数组时未定义感到困惑。

ProfileApp.js

class ProfileApp extends React.Component {
  constructor(props) {
    super(props)
   .........(Truncated for brevity)
   .........(Truncated for brevity)
   }
   componentWillMount() {

   .........(Truncated for brevity)
   this.props.likePets(this.state.currentIndex);
   .........(Truncated for brevity)
   this.props.dislikePets(this.state.currentIndex);



   }
   function mapStateToProps(state){
     return {
       likedPets: state.likedPets,
       dislikedPets: state.dislikedPets
     }
   }
   function mapDispatchToProps(dispatch){
     return{
       likePets: (i)=> dispatch({type:'LIKE_PETS'}),
       dislikePets: (i)=> dispatch({type:'DISLIKE_PETS'})
     }

   }
   export default connect(mapStateToProps)(ProfileApp)

App.js

import  ProfileApp  from './src/ProfileApp';
import {Provider} from 'react-redux';/
const initialState = {
  likedPets: [],
  dislikedPets: []

}
const reducer = (state = initialState, action) =>{

console.log(state.likedPets)
console.log(state.dislikedPets)

  switch (action.type){

    case 'LIKE_PETS':
    return{likedPets: likedPets.push(action.index)}
    case 'DISLIKE_PETS':
    return{dislikedPets:dislikedPets.push(action.index)}
  }
  return state

}

const store = createStore(reducer);
export default class App extends React.Component {



  render() {
    return (
    <Provider store = {store}>
      <ProfileApp></ProfileApp>
    </Provider>

    )
  }
}
我第一次在控制台上编译此代码时的

输出如下: 在初始加载期间:

Array []
Array []
Running application "main" with appParams:.....(Trimed)

用户操作:像宠物一样

Array []
Array []

用户操作:像其他宠物一样

1
undefined

1 个答案:

答案 0 :(得分:0)

您需要在connect中传递mapDispatchToProps:

BeginPaint

export default connect(mapStateToProps)(ProfileApp)

您需要在化简器中传播状态:

export default connect(mapStateToProps, mapDispatchToProps)(ProfileApp)

return{likedPets: likedPets.push(action.index)}

否则,您将使用一个没有您的不喜欢的宠物的对象覆盖商店中的状态。

此外,数组的push方法还返回数组的长度。替换为

return{...state, likedPets: likedPets.push(action.index)}

要获取具有当前状态(likedPets)的数组,并在其中添加action.index。