react 自身不带redux 需要下载
一、下载状态机
yarn add redux react-redux
readx : 状态机
react-redux : react适配redux中间件
二、状态机初始化
index.js
import {combineReducers, legacy_createStore} from 'redux'
import { goodsReducer } from './goods/goodsStore';
const allReducers = combineReducers({
goodsState : goodsReducer
})
const store = legacy_createStore(allReducers);
export default store;
较新的版本中使用 legacy_createStore
旧版本中使用 createStore
combineReducers 函数是将多个值定义到状态机中
goodsStore.js
const initData = [];
export const goodsReducer = (state = initData, action) => {
switch(action.type){
case 'ADD_GOODS' :
console.log("ADD");
return [
...state,
action.payloed
]
default :
return state;
}
}
三、组件中使用状态机的值
函数组件:
1.现在 main.jsx 中配置全局的 store
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import { Provider } from 'react-redux'
import store from './store/index.js'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
)
2、组件中 使用 useSelector 函数来获取参数、useDispath 函数来修改参数
import { Button } from 'antd';
// eslint-disable-next-line no-unused-vars
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
function ReduxTest() {
const goods = useSelector( (state) => {
return state.goodsState;
})
const dispatch = useDispatch();
const updateGoods = () => {
dispatch({
type : 'ADD_GOODS',
payloed : {
id : 1,
name : '测试',
num : 12
}
})
}
return (
<div>
redux data :{goods}
<Button onClick={updateGoods}> 修改 redux </Button>
</div>
)
}
export default ReduxTest
类组件操作:
通过 react-redux 中的 connect 函数与 redux 建立连接,通过connect函数状态机中的数据会存入 props 属性中
// eslint-disable-next-line no-unused-vars
import React, { Component } from 'react'
import AddGoods from './AddGoods'
import {connect} from 'react-redux'
class AntdTest extends Component {
dispath = this.props.dispatch;
render() {
console.log(" render 重新渲染");
console.log(this.props.goodsState);
return (
<div>
<h1>Class 组件练习</h1>
<AddGoods clickFun={this.clickFun}></AddGoods>
<Table rowSelection={{type : 'checkbox'}} dataSource={this.props.goodsState} columns={this.columns} rowKey={'id'} ></Table>
<Button onClick={() => {
this.dispath({
type : 'ADD_GOODS',
payloed : {
id : 1,
name : '测试',
num : 12
}
})
}} >修改 redux </Button>
</div>
)
}
}
// eslint-disable-next-line react-refresh/only-export-components
export default connect( (state) => (
{
goodsState : state.goodsState //获取 redux 中的数据
}),
)(AntdTest);