redux 应用 及动态绑定
创建 store.js 数据
import { createStore } from 'redux'
export const defaultValue = {
visible: false,
getCount: 11,
list: [
{ aa: 222, bb: 333, cc: 2222 },
{ aa: 222, bb: 333, cc: 2222 }
]
}
export const reducer = (state = defaultValue, action) => {
switch (action.type) {
case 'changeVisible':
return Object.assign({}, state, { visible: action.value })
case 'changeTime':
return Object.assign({}, state, { getCount: 'hello' })
default:
return state
}
}
export const store = createStore(reducer)
创建 A组件
import React, { useState } from 'react'
import B from './B'
import store './store.js
export default function A() {
const [state, setState] = useState(store.getState())
const watchState = () => {
setState(store.getState())
}
// 监听 stores 数据变化
stores.subscribe(() => { watchState() })
return (
<div>
<buttom
onClick={() => {
store.dispatch({ type: 'changeVisible', value: 'A组件改变的值'
}) }}>
changeA
</buttom>
<p>A:{state.visible}</p>
<B />
</div>
)
}
创建 B 组件
import React, { useState } from 'react'
import store './store.js
export default function B() {
const [state, setState] = useState(store.getState())
const watchState = () => {
setState(store.getState())
}
stores.subscribe(() => { watchState() })
return (
<div>
<buttom
onClick={() => {
store.dispatch({ type: 'changeVisible', value: 'B组件改变的值'
}) }}>
changeA
</buttom>
<p>B:{state.visible}</p>
</div>
)
}