useSelector Redux挂钩的使用

时间:2019-09-21 14:03:11

标签: reactjs redux react-redux react-hooks

我在Redux挂钩中设置了状态,我不知道如何导入或使用Selector我想要的状态

enter image description here

我在登录文件

中使用useSelector 发送状态
function Login(props) {

var classes = useStyles();
var dispatch = useDispatch();

const { username, password } = useSelector((state) => ({
    ...state.combineReducers,
    ...state.userReducer,
}));

这是 nav文件 在这里,我要了解状态

function nav(props) {

    const { username } = useSelector((state) => ({
        ...state.combineReducers,
        ...state.userReducer,
    }));

错误

 Failed to compile.

./src/NAVBAR/nav.js
  Line 27:  React Hook "useSelector" is called in function "nav" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

我已经尝试了很多方法,但是失败了

2 个答案:

答案 0 :(得分:1)

问题在于nav功能,而不是功能组件

根据您的情况,您可能想制作一个custom-hook

function useUsername() {
  const { userName } = useSelector(state => ({
    ...state.combineReducers,
    ...state.userReducer
  }));
  return { userName };
}

function Login(props) {
  const { userName } = useUsername();
  return <>...</>;
}

请注意,如果要使其成为功能组件,则需要返回ReactElement并在React导入范围内。

import React from 'react';

//        v Note that you must have an Upper-case for it to be a valid ReactElement
function Nav(props) {
  const { username } = useSelector(state => ({
    ...state.combineReducers,
    ...state.userReducer
  }));

  // return ReactElement
  return <>I'm some Element</>;
}

export default Nav;

答案 1 :(得分:0)

我遇到了类似的问题,并找到了一个简单的解决方案。

const username = useSelector(state => state.userReducer.username) 

因此,我们从reducer取得了特定的用户名状态。这对我有用:)