Redux基础小结

96 阅读1分钟
import React from 'react'
import store from './store'
// import axios from 'axios'
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)
    // 1. 一开始这个state就是reducer里面的默认原始值
    // 2.之后不同的事件函数通过dispatch派发一个action,可以通过添加一个变化听器(subscribe)
    // 每当 dispatch action 的时候就会执行,state 树中的一部分可能已经变化。可以在store.subscribe的回调函数(listener)里调用 getState() 来拿到当前 state。在通过setState做数据更新
    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对数据最更新处理