英文:
Redux, state not defined
问题
以下是代码的翻译部分:
Console error:
控制台错误:
Uncaught TypeError: state.options is undefined
未捕获的类型错误:state.options 未定义
Provider setup:
提供程序设置:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { store } from "./Utilities/store";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<>
</>
);
英文:
trying to make an option to change the color of text,border,background but i get the error state is not defined in the console.it says that state.options.text that i addressed in option page is not defined,
i checked the routing and it is Ok
option page
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {textCH, borderCh, backgroundCh} from '../Utilities/options/theme'
function Options() {
const textcolor = useSelector((state)=>state.options.text)
console.log(textcolor);
return (
<div style={{ paddingLeft: '20px' }}>
<h1>OPTIONS</h1>
text color: <input type={'color'} />
border color: <input type={'color'} />
background color: <input type={'color'} />
</div>
)
}
export default Options
Reducer
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
text:'#000000',
border:'#000000',
background:'#FFFFFF',
}
export const optionsSlice = createSlice({
name: 'options',
initialState,
reducers: {
textCH: (state,action) => {
state.text = action.payload
},
borderCh: (state,action) => {
state.border = action.payload
},
backgroundCh: (state, action) => {
state.background = action.payload
},
},
})
export const { textCH, borderCh, backgroundCh } = optionsSlice.actions
export default optionsSlice.reducer
Store file
import { configureStore } from '@reduxjs/toolkit'
import {optionsSlice} from './options/theme'
export const store = configureStore({
reducer: {
options: optionsSlice,
},
})
Console error:
Uncaught TypeError: state.options is undefined
textcolor Options.jsx:6
Provider setup:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import {store} from "./Utilities/store";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<>
<Provider store={store}>
<App />
</Provider>
</>
);
答案1
得分: 1
你在 store.js
中导入了切片本身,而不是 reducer。
不要调用命名的函数:
import { optionsSlice } from './options/theme';
我们应该调用默认的:
import optionsSlice from './options/theme';
英文:
You're importing the slice itself in the store.js
, not reducer.
instead of calling the named function:
import {optionsSlice} from './options/theme'
we should call the default one:
import optionsSlice from './options/theme'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论