1.创建store文件夹,分别创建子文件夹actions和reducers
2。创建constant.js
/*
该模块是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错
*/
export const CHANGEVALUE = 'change_value'
3.store.js
import { legacy_createStore as createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducers from "./reducers";
export default createStore(reducers, applyMiddleware(thunk))
4.reducers创建index.js和redux_test.js
redux_test.js
import { CHANGEVALUE } from "../constant";
//定义一个默认状态
const defaultState = {
msg: "你好,世界"
}
//导出一个函数
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = defaultState, action) => {
//从action对象中获取:type、data
const { type, data } = action
let newState = JSON.parse(JSON.stringify(state))//使用深拷贝,不然数据不变化
switch (type) {
case CHANGEVALUE:
newState.msg = state.msg + data;
break
default:
break
}
return newState
}
index.js
/*
该文件用于汇总所有的reducer为一个总的reducer
*/
//引入combineReducers,用于汇总多个reducer
import { combineReducers } from 'redux'
import redux_test from './redux_test'
//汇总所有的reducer变为一个总的reducer
export default combineReducers({
redux_test
})
5.reducers创建redux_test.js
import { CHANGEVALUE } from "../constant"
/*
该文件专门为Count组件生成action对象
*/
//同步action,就是指action的值为Object类型的一般对象
export const changeValue = data => ({ type: CHANGEVALUE, data })
测试=====
index.js使用Provider监听redux,传入store
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';//redux
import App from './App';
import store from './store/store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
/* 此处需要用Provider包裹App,目的是让App所有的后代容器组件都能接收到store */
<Provider store={store}>
<App />
</Provider>
);
所有使用redux的组件放在containers目录下
创建ReduxTest组件,redux父组件与子组件使用connect连接
import React, { Fragment } from 'react'
import { connect } from 'react-redux'
import { changeValue } from '../../store/actions/redux_test'
function ReduxTest(props) {
return (
<Fragment>
<div>
{props.msg}
</div>
<button onClick={() => props.changeValue('----->hello')}>修改显示</button>
</Fragment>
)
}
//使用connect()()创建并暴露一个Count的容器组件
export default connect(
state => ({
msg: state.redux_test.msg
}),
{
changeValue
}
)(ReduxTest)