gpt4 book ai didi

reactjs - 使用 useSelector redux hooks

转载 作者:行者123 更新时间:2023-12-02 16:52:16 25 4
gpt4 key购买 nike

我在 redux hooks 中创建状态我不知道如何导入或使用 Selector 我想要的状态

enter image description here

这里我在登录文件

中使用useSelector Send to state
function Login(props) {

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

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

那是导航文件在这里我想获取状态

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

我试过很多方法都失败了

最佳答案

问题是 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;

关于reactjs - 使用 useSelector redux hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com