1.创建store文件夹,文件夹下创建index.jsx和reducer.jsx
reducer.jsx
//定义一个默认状态
const defaultState = {
msg: "你好,世界"
}
//导出一个函数
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = defaultState, action) => {
let newState = JSON.parse(JSON.stringify(state))//使用深拷贝,不然数据不变化
switch (action.type) {
case 'changeValue':
newState.msg = action.data;
break
default:
break
}
return newState
}
index.jsx
import { legacy_createStore as createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer)
export default store
2.index.js中使用Provider包裹并加入store
3.使用connect,连接redux父容器与子容器
import React, { Fragment } from 'react'
import { connect } from 'react-redux'
function App(props) {
return (
<Fragment>
<div>
{props.msg}
</div>
<button onClick={() => props.changeValue('hello')}>修改显示</button>
</Fragment>
)
}
const mapStateToProps = (state) => {
return {
msg: state.msg
}
}
const mapDispatchToProps = (dispatch) => {
return {
changeValue(msg) {
const action = { type: 'changeValue', data: msg }
dispatch(action)
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)