Object(...)不是函数

时间:2018-07-08 00:12:58

标签: reactjs redux react-redux

我通过遵循一些教程来学习redux。在这里我得到一个错误

  

Object(...)不是函数

在此行

export default connect(null, { fetchPosts } )(Posts);

以下容器的

import React, { Component } from 'react';
import { connect } from 'react'
import axios from 'axios';
import { fetchPosts } from '../actions/postActions.js';

class Posts extends Component {
  componentWillMount() {
    this.props.fetchPosts();
  }
  render() {
    const postItems = this.state.posts.map(el => {
      return (
        <div key={el.id}>
        <h3>{el.title} </h3>
        <p>{el.body} </p>
        </div>
      )
    })
    return (
      <div>
      <h1> Posts </h1>
      {postItems}
      </div>
    );
  }

}

export default connect(null, { fetchPosts } )(Posts);

Ps:我知道它也会引发地图错误,但目前我并不担心。

由于它说 Object(...)不是函数并标记了行导出,因此我们在导出中唯一拥有的对象是看起来像这样的fetchPosts(它是一个动作函数)

import { FETCH_POST, NEW_POST } from './type.js'
import axios from 'axios';

export const fetchPosts = () => {
  return function (dispatch) {
    axios.get("https://jsonplaceholder.typicode.com/posts").then((response) => dispatch({
      type: FETCH_POST,
      payload: response
    }))
  }

}

由于我不确定相同的相关代码,因此fetchPosts将acton调度到以下reducer

    import { FETCH_POST, NEW_POST } from '../actions/type.js'
const initialState = {
  items: [],
  item: {}
}
    export default function(state = initialState, action) {
  switch (action.type) {
    case FETCH_POST:
      return {
        ...state,
        items: action.payload
      }
      default:
        return state
  }

}

稍后会在我们的rootreducer.js文件(然后将其导入到我们创建商店的store.js文件)中使用CombineReducers进行合并

谁能告诉我我在做什么错,我们该如何解决?

1 个答案:

答案 0 :(得分:2)

React没有命名的connect导出,它属于react-redux。因此,您应该这样导入它:

import { connect } from "react-redux";