我使用redux工具包用createSlice创建了一个切片。
import { createSlice } from "@reduxjs/toolkit";
export const selectAppColorChange = state => state.lightMode;
const appColorChangeSlice = createSlice({
name: 'appColorChange',
initialState: {lightMode: true},
reducers: {
changeState: state => {
state.lightMode = state.lightMode ? false : true;
}
}
});
export const { changeState } = appColorChangeSlice.actions;
export default appColorChangeSlice.reducer;然后,我创建了一个按钮,初始状态为太阳图像,当点击和相反的时候,它将自己变成月亮图像。
import Sun from '../../images/icon-sun.svg';
import Moon from '../../images/icon-moon.svg';
import { useSelector, useDispatch } from 'react-redux';
import { selectAppColorChange, changeState } from '../App/appColorChangeSlice';
export function TodoHeader(){
const dispatch = useDispatch();
const buttonIconBool = useSelector(selectAppColorChange);
function changeBackground () {
dispatch(changeState());
console.log(buttonIconBool);
}
return (
<div className='todoHeader'>
<h1>TODO</h1>
<img className='changeColorButton'
src={buttonIconBool ? Sun : Moon}
onClick={changeBackground}
alt='change_state_button'/>
</div>
)
}但是出现了一个错误,月亮总是出现,当我点击月球时,月亮就会保持不变,以找到更多的信息,并将I console.log(buttonIconBool)问题修复到控制台。而不是给出我想要的布尔值,而是返回未定义的值。我怎么才能解决这个问题?谢谢你回答我的问题!
发布于 2022-10-07 10:03:20
看来你选错了。
假设你在你的store.js里给了store.js这样的东西,
import appColorChange from "******/appColorChange**.js";
export const store = configureStore({
reducer: {
appColorChange: appColorChange
},
})那么选择器应该是,
export const selectAppColorChange = state => state.appColorChange.lightMode;或
const buttonIconBool = useSelector(state => state.appColorChange.lightMode);将调用选择器,其唯一参数是整个Redux状态。
https://stackoverflow.com/questions/73985426
复制相似问题