Flux与Redux
Flux是一种架构思想,专门解决软件的结构问题。与MVC架构是同一类东西,但是更加简单和清晰,Flux至少有15种实现方式
Redux工作基本流程
1、创建reducer函数,设置旧的prevState和action参数,修改状态应该创建新的状态,不要修改旧状态,通过action的type字段,决定对状态做什么操作,返回什么样的状态,把reducer函数传给createStore函数。 2、通过createStore函数创建store(不过快用不了了,提示弃用了) 3、在需要的地方通过store进行订阅,通过store.getState()获取状态对象 4、在需要发送的地方通过store.dispatch,并设type字段告诉reducer要执行什么 以下是基本代码 store.jsx
// 1.引入redux
import {createStore} from 'redux'
const reducer = (prevState={
show:'hide'
}, action) => {
console.log(action);
const newState = {...prevState}
switch (action.type) {
case 'hide':
newState.show = 'hide'
return newState
default:
return prevState
}
}
// 2.创建Store
const store = createStore(reducer)
export default store
ReduxTest.jsx 订阅位置
export default class ReduxTest extends Component {
componentDidMount() {
store.subscribe(() => {
console.log('订阅', store.getState());
})
}
render() {
return (
<div>ReduxTest
<RdTs></RdTs>
</div>
)
}
}
RdTs.jsx 发送位置
import React, { useEffect } from 'react'
import store from './redux/store';
export default function RdTs() {
useEffect(() => {
store.dispatch({
type: 'hide'
})
return () => {
console.log('销毁');
}
}, [])
return (
<div>RdTs</div>
)
}
运行结果