【问题标题】:Error: Element type is invalid: expected a string or a class/function but got: undefined错误:元素类型无效:应为字符串或类/函数,但得到:未定义
【发布时间】:2020-11-11 02:27:24
【问题描述】:

Error image错误具体指向:

dispatch({
   type: SET_POSTS,
   payload: res.data
})

下面是我的函数代码:

export const getPosts = () => dispatch => {
    dispatch({ type: LOADING_DATA })
    axios.get('/posts')
        .then(res => {
            dispatch({
                type: SET_POSTS,
                payload: res.data
            })
        })
        .catch(err => {
            dispatch({
                type: SET_POSTS,
                payload: []
            })
        })
};

我检查了导入,console.log(res),一切似乎都很好,但错误总是指向 dispatch()

编辑: 在使用 redux 开发工具跟踪代码后,我发现 SET_POSTS 的有效负载不断从 payload:[{...}] 变为未定义。下面我附上了我的减速器的代码。我还是不知道是什么问题。

import { SET_POSTS, LIKE_POST, UNLIKE_POST, LOADING_DATA } from '../types';

const initialState = {
    posts: [],
    post: {},
    loading: false,
};

export default function (state = initialState, action) {
    switch (action.type) {
        case LOADING_DATA:
            return {
                ...state,
                loading: true
            };
        case SET_POSTS:
            return {
                ...state,
                posts: action.payload,
                loading: false,
            };
        case LIKE_POST:
        case UNLIKE_POST:
            var index = state.posts.findIndex((post) => post.postId === action.payload.postId);
            state.posts[index] = action.payload;
            // conditional from github
            if (state.post.postId === action.payload.postId) {
                state.post = action.payload;
            }
            return {
                ...state
            };
        default:
            return state;
    }
}

这里是 getPosts() 函数被渲染的地方:

import { getPosts } from '../redux/actions/dataActions';

class home extends Component {

    componentDidMount() {
        this.props.getPosts();
    }
    render() {
        const { posts, loading } = this.props.data;
        let recentPostsMarkup = !loading ? (
            posts.map(post => <Post key={post.postId} post={post} />)
        ) : (<p>loading...</p>);
return (
            <Grid container spacing={5}>
                <Grid item sm={8} xs={12}>
                    {recentPostsMarkup}
                </Grid>
                <Grid item sm={4} xs={12}>
                    <Profile />
                </Grid>
            </Grid>
        );

home.propTypes = {
    getPosts: PropTypes.func.isRequired,
    data: PropTypes.object.isRequired,
}

const mapStateToProps = state => ({
    data: state.data
});
export default connect(mapStateToProps, { getPosts })(home);

这是 Post.js 文件,post 属性在 home.js 文件中传递。

class Post extends Component {
    likedPost = () => {
        if (this.props.user.likes && this.props.user.likes.find(
            like => like.postId === this.props.post.postId)
        ) return true;
        else return false;
    };
    likePost = () => {
        this.props.likePost(this.props.post.postId);
    }
    unlikePost = () => {
        this.props.unlikePost(this.props.post.postId);
    }
    render() {
        dayjs.extend(relativeTime);
        const {
            classes,
            post: { body, createdAt, userImage, userHandle, postId, likeCount, commentCount },
            user: {
                authenticated
            }
        } = this.props;
        const likeButton = !authenticated ? (
            <MyButton tip="Like">
                <Link to="/login">
                    <FavoriteBorder color="primary"/>
                </Link>
            </MyButton>
        ) : (
            this.likedPost() ? (
                <MyButton tip="Undo like" onClick={this.unlikePost}>
                    <FavoriteIcon color="primary"/>
                </MyButton>
            ): (
                <MyButton tip="Like" onClick={this.likePost}>
                    <FavoriteBorder color="primary"/>
                </MyButton>
            )
        )
        return (
            <Card className={classes.card}>
                <CardMedia
                    image={userImage}
                    title="Profile Image" className={classes.image} />
                <CardContent className={classes.content}>
                    <Typography
                        variant="h5"
                        component={Link}
                        to={`/users/${userHandle}`}
                        color="primary">
                        {userHandle}
                    </Typography>
                    <Typography variant="body2" color="textSecondary">
                        {dayjs(createdAt).fromNow()}
                    </Typography>
                    <Typography variant="body1">
                        {body}
                    </Typography>
                    {likeButton}
                    <span>{likeCount} Likes</span>
                    <MyButton tip="comments">
                        <ChatIcon color="primary" />
                    </MyButton>
                    <span>{commentCount} comments</span>
                </CardContent>
            </Card>
        )
    }
};


【问题讨论】:

  • 当你从 .then() 调用中移除调度时会发生什么?
  • 如果我删除它,它就不会获取帖子或数据。不会出现任何错误。
  • 我认为调度本身可能没问题,但是在组件中渲染元素时存在问题,该组件根据 SET_POSTS 操作中发送的数据呈现(我假设)列表。堆栈跟踪有时可能会令人困惑或指向一些奇怪的东西。你能提供一个渲染这些元素的组件代码吗?
  • 我在上面提供了编辑。我检查了 getPosts() 的渲染位置,一切都很好。 SET_POSTS 用于减速器,看起来也不错,我会提供代码,但 stackoverflow 说它的代码太多。
  • 似乎您没有从组件的render() 函数返回任何内容。在render() 的末尾添加return recentPostsMarkup,它应该可以工作。

标签: reactjs react-redux axios dispatch


【解决方案1】:

Ciao,这是 React 中众所周知的问题。请检查这个guide(即使是为 React Native 制作的)。 简而言之,您的问题与您如何导入组件有关,与您如何分派数据无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 2021-01-18
    • 2020-08-09
    • 2020-07-18
    • 2021-01-20
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多