首页 > 解决方案 > 如何在 Redux 工具包中设置状态(!状态)

问题描述

我是 RTK 新手,最近几天一直在学习教程,我知道如何处理数组,并增加或减少值,但我无法理解 RTK 中最简单的事情是切换状态。到目前为止,我已经编写了这段代码:

 import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    dropdown: false
}

const dropdownSlice = createSlice({
    name: 'dropdown',
    initialState,
    reducers: {
        setDropdown: state  =>  !state
    }
});

export const {
    setDropdown
} = dropdownSlice.actions
export default dropdownSlice.reducer

然后在我的组件中我做了这个

import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
import {GiHamburgerMenu} from 'react-icons/gi'
import {useDispatch} from 'react-redux'
import { setDropdown } from '../../redux/slices/dropdownSlice'
import dropdownSlice from '../../redux/slices/dropdownSlice'
import './Nav.scss'


        const Nav = () => {
            const [width,setWidth] = useState(window.innerWidth)
            // const [dropdown,setDropdown] = useState(false);
            const dispatch = useDispatch()
            const checkDropdown = () =>{
              dispatch(setDropdown);
            }
        
            const checkWidth = () =>{
                setWidth(window.innerWidth)
                // if(width > 600){
                //     setDropdown(false);
                // }
                // console.log(width);
            }
            useEffect(() =>{
                window.addEventListener('resize', checkWidth)
                return () => window.removeEventListener('resize',checkWidth)
            },[])
            return (
              <nav>
                <header>
                  <div className="logo">
    ....
                  </div>
                  <div className="links">
                      {width > 600 ?
                    <ul>
                      ....
                    </ul>
                    :
                    <GiHamburgerMenu className='icon' onClick={()=> checkDropdown()}/>}
                  </div>
                </header>
                <div
                  className={
                    dropdownSlice.dropdown ? "dropdown dropdown-show" : "dropdown dropdown-hide"
                  }
        .............
                    >

请帮忙,我在 2 天内已经老了 3 岁,试图学习 rtk

标签: reactjsredux-toolkit

解决方案


两个错误:

  1. 您的减速机无法保持其形状。它从{ dropdown: false }falsetruefalsetrue

这是{ dropdown: false }<->{ dropdown: true }

const initialState = {
    dropdown: false
}

const dropdownSlice = createSlice({
    name: 'dropdown',
    initialState,
    reducers: {
        setDropdown: (state) => { state.dropdown = !state.dropdown }
    }
});

这是false<-> true

const initialState = false

const dropdownSlice = createSlice({
    name: 'dropdown',
    initialState,
    reducers: {
        setDropdown: state => !state
    }
});
  1. 你需要在调度之前执行你的动作创建者
dispatch(setDropdown());

推荐阅读