$ npm install -SE react-redux @reduxjs/toolkit
Создаем слайс, который будет хранить состояние
// src/slices/color.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
color : ''
} ;
export const ColorSlice = createSlice ( {
name : 'color' ,
initialState,
reducers : {
setColor : ( state , action ) => {
state . color = action . payload ;
}
} ,
selectors : {
getColor : ( state ) => state . color ,
}
} ) ;
export const ColorReducer = ColorSlice . reducer ;
export const {
getColor
} = ColorSlice . selectors ;
Создаем центральное хранилище
// src/store/index.js
import { combineReducers , configureStore }
from '@reduxjs/toolkit' ;
import { ColorSlice } from '../slices/color'
const reducer = combineReducers ( {
[ ColorSlice . reducerPath ] : ColorSlice . reducer ,
} ) ;
export const store = configureStore ( {
reducer,
} )
Подключаем его в приложение
// src/App.jsx
// ...
import { store } from './store/index'
const App = ( ) => {
return (
< BrowserRouter >
< Provider store = { store } >
...
</ Provider >
</ BrowserRouter >
)
}
Теперь мы можем сохранять состояние в store и читать оттуда
// src/pages/page2.jsx
import { ColorSlice , getColor } from '../slices/color'
import { useSelector , useDispatch } from 'react-redux'
export const Page2 = ( ) => {
const color = useSelector ( getColor ) ;
const { setColor } = ColorSlice . actions ;
const dispatch = useDispatch ( ) ;
const updateColor = ( value ) => {
dispatch ( setColor ( value ) )
} ;
return (
< >
< Semaphore color = { color } setColor = { updateColor } />
</ >
)
}
Понятное дело, придется убрать собственное состояние из переключателя
// src/.../Semaphore.jsx
export const Semaphore = ( { color, setColor } ) => {
return (
< >
< NameInput color = { color } setColor = { setColor } />
</ >
)
}