【问题标题】:React Hook "useSelector" is called in function "posts" that is neither a React function component nor a custom React Hook functionReact Hook "useSelector" 在函数 "posts" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数
【发布时间】:2022-01-12 08:01:00
【问题描述】:
Posts.js

import React from 'react'
import Post from './Post/Post'
import UseStyles from "./style"
import {useSelector} from "react-redux"
function posts() {
    const classes= UseStyles()
    const Posts=useSelector((state)=>state.Posts)       //This state refers the to the whole redux store and in this state.Post, post is coming form the Reducers/index.js
    console.log(Posts)
    return (
        <div>
            <h1>POSTS</h1>
            <Post/>
            <Post/>
        </div>
    )
}

export default posts

index.js

import { combineReducers } from "redux";
import Posts from "./Posts";
export default combineReducers({ Posts })

src\Components\Posts\Posts.js 第 7:17 行:React Hook "useSelector" 在函数 "posts" 中被调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数。 React 组件名称必须以大写字母开头。 React Hook 名称必须以 "use" react-hooks/rules-of-hooks 开头

这是实际错误。起初它是这个错误中提到的 state.posts 然后我改变了它,仍然显示同样的错误,我也重新启动了我的服务器,但没有任何新的事情发生。

【问题讨论】:

  • 将它从帖子更改为帖子,看看会发生什么
  • 为什么要将 Posts 组件合并到减速器中?

标签: reactjs react-redux


【解决方案1】:

正确的 React 组件是 PascalCased。您还应该将控制台日志移动到useEffect,这样在原本被视为纯函数的情况下,这是有意的副作用。

...
import useStyles from "./style"
...

function Posts() {
  const classes = useStyles();
  const posts = useSelector((state) => state.Posts);

  useEffect(() => {
    console.log(posts);
  }, [posts])'
  
  return (
    <div>
      <h1>POSTS</h1>
      <Post/>
      <Post/>
    </div>
  );
}

export default Posts;

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 2019-09-14
    • 2020-11-02
    • 1970-01-01
    • 2020-07-04
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多