reactjs - 如何在 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
解决方案
两个错误:
- 您的减速机无法保持其形状。它从
{ dropdown: false }
到false
到true
到false
。true
这是{ 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
}
});
- 你需要在调度之前执行你的动作创建者
dispatch(setDropdown());
推荐阅读
- javascript - 每次测试破坏 Puppeteer 测试后的屏幕截图
- .htaccess - 没有 .htaccess 的 404 页面
- audio - Audio Unit RemoteIO Setting interleaved float 给出 kAudioUnitErr_FormatNotSupported
- javascript - 为什么立即调用的函数表达式中的函数不需要名称?
- javascript - 仅当该数组中的对象存在于另一个数组中时才返回对象数组
- docusignapi - Docusign API:在“这里”或“那里”签名,需要一个,而不是两个
- swiftui - SwiftUI 线规
- java - 为什么在子类中无法通过超类实例访问受保护的成员?
- go - 如何将 TestMain(m *testing.M) 限制为当前测试文件
- amazon-web-services - 当我将 zip 文件上传到 elasticbeanstalk 时,到底发生了什么?