import React from 'react'
import store from './store'
import { initData } from './action'
import { Input, Button, Divider, List } from 'antd'
import 'antd/dist/antd.css'
class App extends React.Component {
constructor(props) {
super(props)
this.state = store.getState()
store.subscribe(this.handleStoreChange)
}
render() {
const { data } = this.state
return (
<>
<Input placeholder='请输入内容' style={{ width: 350 }} />
<Button type='primary'>点击按钮</Button>
<div style={{ width: 480 }}>
<Divider orientation='left'>Default Size</Divider>
<List
bordered
dataSource={data}
renderItem={(item) => <List.Item>{item}</List.Item>}
/>
</div>
</>
)
}
componentDidMount() {
const data = ['hello', 'world', 'jenson']
const initDataAction = initData(data)
store.dispatch(initDataAction)
}
handleStoreChange = () => {
this.setState(store.getState())
}
}
export default App
- 之前不知道为什么需要在constructor进行this.state = store.getState(),后面通过查看文档并进行实验,发现这里一开始拿到的值就是reducer里面的默认值,这其实就像是没有用redux时,通过在constructor里面直接定义this.state对象
- 之后一些事件函数通过dispatch派发一些action的时候,会造成一些数据改变,这时候呢就可以通过变化监听器subscribe监听这个state树的改变,然后可以传入一个listener回调函数,这个函数可以拿到新的state值,通过setState对数据最更新处理