我正在学习redux工具包。我无法解决这个错误。请帮助我。
error screenshot
贮藏
import { createSlice, configureStore } from "@reduxjs/toolkit";
const initialState = { counter: 0, showCounter: true };
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment (state) {
state.counter++;
},
decrement (state) {
state.counter--;
},
increase (state,action) {
state.counter = state.counter+ action.payload;
},
toogleCounter (state) {
state.showCounter = !state.showCounter;
}
}
});
const store = configureStore({
reducer: { counter: counterSlice.reducer }
});
export const counterActions = counterSlice.actions;
export default store;
Counter.jsx
import { useSelector, useDispatch } from 'react-redux';
import { counterActions } from '../store';
import classes from './Counter.module.css';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector(({ counter }) => counter);
const incrementHandler = () => {
dispatch(counterActions.increment());
};
const decrementHandler = () => {
dispatch(counterActions.decrement());
};
const increaseHandler = () => {
dispatch(counterActions.increase(10));
};
const toggleCounterHandler = () => {};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{counter}</div>
<div>
<button onClick={incrementHandler} >Increment</button>
<button onClick={increaseHandler} >Increment by 10</button>
<button onClick={decrementHandler} >Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
这是我正在处理的sample-project,这将在您的机器上重现错误。
我试着在谷歌上搜索这个错误,但它显示的结果没有解决我的问题。
1条答案
按热度按时间gr8qqesn1#
counter
是一个对象,并且对象不是有效的JSX。如果您只想呈现state.counter.counter
值,则进一步访问选定状态。从state.counter
中解构counter
应该足够了。const { counter } = useSelector(({ counter }) => counter);
示例: