赞
踩
npm install redux react-redux @reduxjs/toolkit --save
import { configureStore } from '@reduxjs/toolkit'
import userSlice from './userReducer'
const store = configureStore({
reducer: {
user: userSlice.reducer
}
})
// 订阅 store
// store.subscribe(() => console.log('subscribe: ', store.getState()))
export default store
import { createSlice } from '@reduxjs/toolkit' const userSlice = createSlice({ name: 'user', initialState: { str: '我是redux未修改前的文字' }, reducers: { editStr(state, action) { // Redux Toolkit 允许在 reducers 中编写 "mutating" 逻辑。 // 它实际上并没有改变 state,因为使用的是 Immer 库,检测到“草稿 state”的变化并产生一个全新的, // 基于这些更改的不可变的 state state.str = action.payload } } }) export default userSlice
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index'
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<Provider store={store}>
<App />
</Provider>
);
import { useSelector, useDispatch } from 'react-redux' import { useNavigate } from 'react-router-dom'; import React, { useState } from 'react'; import { Button } from 'antd'; const Home: React.FC = () => { const navigate = useNavigate(); const { str } = useSelector((state:StoreType.State) => state.user) let dispatch = useDispatch() const [msg] = useState<string>('点击改变redux'); const handleChange = () => { dispatch({ type: 'user/editStr', payload: '我是工作台修改redux后的值' }) } return ( <> <h1>工作台</h1> <Button type="primary" onClick={handleChange}>{msg}</Button> <Button type="primary" onClick={() => navigate('/authMag/userMag')}>跳转到用户页面</Button> <h1>{str}</h1> </> ) } export default Home
import React from "react" import { Button } from 'antd'; import { connect } from "react-redux"; import { Link } from 'react-router-dom' type PropType = { user: { str: string }, dispatch: Function } type StateType = { msg: string } class User extends React.Component<PropType, StateType> { constructor(props: PropType | Readonly<PropType>) { super(props) this.state = { msg: '点击改变redux' } } componentDidMount() { console.log('User-componentDidMount') } handleChange = () => { this.props.dispatch({ type: 'user/editStr', payload: '我是User页修改redux后的值' }) } render() { const { msg } = this.state const { str } = this.props.user return ( <> <h1>用户管理</h1> <Button type="primary" onClick={this.handleChange}>{msg}</Button> <Button type="primary"> <Link to="/home">跳转到工作台页面</Link> </Button> <h1>{str}</h1> </> ) } } const mapStateToProps = (state:PropType) => ({ user: state.user }); const mapDispatchToProps = (dispatch: Function) => ({ dispatch }); export default connect(mapStateToProps, mapDispatchToProps)(User);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。