简体   繁体   中英

TypeError: undefined is not a function (evaluating userItems.map)

Edit: Now i'm using "react-native-navigation@latest" everything is fine.

When i open the app first time it is fething data properly but after second refresh error occured

TypeError: undefined is not a function (evaluating 'userItems.map')

this error is located at:
in Users (created by Connect(Users));
....

....

Component/Users.js

  componentWillMount(){
    this.props.fetchUsers();
  }

  render() {
    const userItems = this.props.users || [];
    const abc = userItems.map((user,index) => (
      <Text key={index}>
      {user.email}
      </Text>
    ));
    return (
      <View>
        {abc}
      </View>
    );
  }
}
const mapStateToProps = state => ({
  users: state.UserReducer.items
})

const mapDispatchToProps = {
  fetchUsers
};


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

Actions

export function fetchUsers() {
  return dispatch => {
    fetch("http://example.com/v1/users")
      .then(res => res.json())
      .then(users =>
        dispatch({
          type: FETCH_USERS,
          payload: users
        })
      );
  };
}

reducer/userReducer.js

import { FETCH_USERS } from "../Actions/types";

    const initialState = {
      items: []
    };

    const userReducer= (state = initialState, action) => {
        switch(action.type){
            case FETCH_USERS:
                return {
                    ...state,
                    items:action.payload
                }
            default:
                return state;
        }
    }
export default userReducer;

reducer/index.js

import UserReducer from './userReducer';
const AppReducer = combineReducers({
  ...
  UserReducer,
  ...
  ...
  ...
});

export default AppReducer;

backend is fine i testes with postman

users backend

  const router = new express.Router();

  router.route("/users").get((req, res) => {
    User.find({},{password:0}, (err, users) => {
      if (err) {
        return res.status(404).send({message: "error"});
        console.log(err);
      } else {
        return res.status(200).send({users});
      }
    });
  });

response backend

{
    "users": [
        {
            "dateCreated": "..",
            "dateModified": "...",
            "lastLogin": "...",
            "_id": "...",
            "email": "...",
            "__v": 0
        },
        {
            "dateCreated": "..",
            "dateModified": "...",
            "lastLogin": "...",
            "_id": "...",
            "email": "...",
            "__v": 0
        }
    ]
}

package.json dependencies

 "dependencies": {
    "asyncstorage": "^1.5.0",
    "es6-promise": "^4.2.4",
    "react": "16.3.1",
    "react-native": "0.55.3",
    "react-native-vector-icons": "^4.6.0",
    "react-navigation": "v1.0.0-beta.26",
    "react-redux": "^5.0.7",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-persist": "^5.9.1",
    "redux-thunk": "^2.2.0"
  },

Are you sure you're mapping your action inside your MapDispatchToProps? (Ideally this post would be a comment but I do not have comment permissions yet).

const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers: () => dispatch(fetchUsers());
    };    
};

If /users response is this :

{
    "users": [
        {
            "dateCreated": "..",
            "dateModified": "...",
            "lastLogin": "...",
            "_id": "...",
            "email": "...",
            "__v": 0
        }
    ]
}

Then when dispatching FETCH_USERS , you should do it like this : (notice the payload property)

export function fetchUsers() {
  return dispatch => {
    fetch("http://example.com/v1/users")
      .then(res => res.json())
      .then(data =>
        dispatch({
          type: FETCH_USERS,
          payload: data.users
        })
      );
  };
}

Or you can do this inside the reducer (notice the items property) :

const userReducer= (state = initialState, action) => {
    switch(action.type){
        case FETCH_USERS:
             return {
                  ...state,
                  items: action.payload.users 
             }
             default:
             return state;
    }
}

It looks like your code is using the react-native-router-flux (which has react-navigation as a dependency), from the code sample given. There is an open issue with this listed on github . The current solution to this, as discussed in this SO answer is to use the beta26 version + of react-native router-flux. I suspect this will solve your problem. If not, well, worth a shot! ..

Hth..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM