即使动作看起来正确,动作也未定义或不可见

时间:2020-01-10 14:01:13

标签: javascript function redux react-redux

我必须对我的切换按钮使用useDispatch(),因此我必须使它们不反应到还原状态。我正在关注Redux的基础教程,我认为我已经正确地做到了,但是当我尝试至少使用Selector来显示按钮的redux'状态时,它什么也没显示。

这是我的代码:

// types.js在动作文件夹中

   export const TOGGLE = "TOGGLE";

// button动作文件夹中的动作

 export const toggle = () => {
return {
type: 'TOGGLE'
};
};

// buttonreduces文件夹中的

const buttonReducer = (state = true, action) => {
 switch(action.type) {
  case 'TOGGLE':
    return !state;
  default:
    return state;
};
};

 export default buttonReducer;

然后将buttonReducer导入到CombineReducers中,以进行存储。

组件代码:

import React, { useState, useEffect } from 'react'
import isloff from './mainpage_imgs/isloff.png'
import islon from './mainpage_imgs/islon.png'
import PropTypes from "prop-types";
import { connect, useDispatch, useSelector } from "react-redux";
import { toggle } from '../../actions/buttonActions'

  const Islbutton = props => {

const [open, setOpen] = useState(true);
const [role, setRole] = useState('');



useEffect(() => {
  if (props.auth.user) 
  { 
    setRole(props.auth.user.role);
  }
}, []);

const test = useSelector(state => state.button);

 const checkRole = (role) => {
  if (role === 'Menager' || role === 'Technolog')
   {
      return true }
    else 
    {
      return false
    };
}

const toggleImage = () => {
if(checkRole(role)) {
setOpen(!open)
};
}

     const getImageName = () => open ? 'islOnn' : 'islOfff'

const dispatch = useDispatch();

            return(

              <div>

                <img style={islplace} src={open ? islon : isloff }          
onClick={()=> dispatch(toggle())} />

              </div>
            );
    }


Islbutton.propTypes = {
button: PropTypes.func.isRequired,
auth: PropTypes.obj.isRequired
};

const mapStateToProps = state => ({
button: state.button,
auth: state.auth
});

export default connect(mapStateToProps, {}), (Islbutton);

1 个答案:

答案 0 :(得分:1)

根据您的最新评论和对用例的理解,我建议采用以下提炼方法:

projectEmployee
project

希望,它为切换全局变量并将其值映射到局部组件状态提供了一个思路。